/*!
    Starts the backend.  Returns \c true if the backend is started.  Returns \c false if the backend
    could not be started due to an unopened or roaming session.  The caller should recall this
    function once the session has been opened or the roaming process has finished.
*/
bool QNetworkAccessBackend::start()
{
#ifndef QT_NO_BEARERMANAGEMENT
    // For bearer, check if session start is required
    QSharedPointer<QNetworkSession> networkSession(manager->getNetworkSession());
    if (networkSession) {
        // session required
        if (networkSession->isOpen() &&
            networkSession->state() == QNetworkSession::Connected) {
            // Session is already open and ready to use.
            // copy network session down to the backend
            setProperty("_q_networksession", QVariant::fromValue(networkSession));
        } else {
            // Session not ready, but can skip for loopback connections

            // This is not ideal.
            const QString host = reply->url.host();

            if (host == QLatin1String("localhost") ||
                QHostAddress(host).isLoopback() ||
                reply->url.isLocalFile()) {
                // Don't need an open session for localhost access.
            } else {
                // need to wait for session to be opened
                return false;
            }
        }
    }
#endif

#ifndef QT_NO_NETWORKPROXY
#ifndef QT_NO_BEARERMANAGEMENT
    // Get the proxy settings from the network session (in the case of service networks,
    // the proxy settings change depending which AP was activated)
    QNetworkSession *session = networkSession.data();
    QNetworkConfiguration config;
    if (session) {
        QNetworkConfigurationManager configManager;
        // The active configuration tells us what IAP is in use
        QVariant v = session->sessionProperty(QLatin1String("ActiveConfiguration"));
        if (v.isValid())
            config = configManager.configurationFromIdentifier(qvariant_cast<QString>(v));
        // Fallback to using the configuration if no active configuration
        if (!config.isValid())
            config = session->configuration();
        // or unspecified configuration if that is no good either
        if (!config.isValid())
            config = QNetworkConfiguration();
    }
    reply->proxyList = manager->queryProxy(QNetworkProxyQuery(config, url()));
#else // QT_NO_BEARERMANAGEMENT
    // Without bearer management, the proxy depends only on the url
    reply->proxyList = manager->queryProxy(QNetworkProxyQuery(url()));
#endif
#endif

    // now start the request
    open();
    return true;
}
Exemple #2
0
void ClientProxy::setCSyncProxy( const QUrl& url, CSYNC *csync_ctx )
{
#ifdef USE_NEON
    /* Store proxy */
    QList<QNetworkProxy> proxies = QNetworkProxyFactory::proxyForQuery(QNetworkProxyQuery(url));
    // We set at least one in Application
    Q_ASSERT(proxies.count() > 0);
    if (proxies.count() == 0) {
        qDebug() << Q_FUNC_INFO << "No proxy!";
        return;
    }
    QNetworkProxy proxy = proxies.first();
    if (proxy.type() == QNetworkProxy::NoProxy) {
        qDebug() << "Passing NO proxy to csync for" << url.toString();
    } else {
        qDebug() << "Passing" << proxy.hostName() << "of proxy type " << proxy.type()
                 << " to csync for" << url.toString();
    }

    csync_set_module_property( csync_ctx, "proxy_type", (void*)(proxyTypeToCStr(proxy.type())));
    csync_set_module_property( csync_ctx, "proxy_host", proxy.hostName().toUtf8().data());
    int proxy_port         = proxy.port();
    csync_set_module_property( csync_ctx, "proxy_port", &proxy_port );
    csync_set_module_property( csync_ctx, "proxy_user", proxy.user().toUtf8().data());
    csync_set_module_property( csync_ctx, "proxy_pwd",  proxy.password().toUtf8().data());
#else
    Q_UNUSED(url);
    Q_UNUSED(csync_ctx);
#endif
}
Exemple #3
0
void QNetworkReplyImplPrivate::_q_networkSessionConnected()
{
    Q_Q(QNetworkReplyImpl);

    if (manager.isNull())
        return;

    QSharedPointer<QNetworkSession> session = manager->d_func()->getNetworkSession();
    if (!session)
        return;

    if (session->state() != QNetworkSession::Connected)
        return;

    #ifndef QT_NO_NETWORKPROXY
        // Re-set proxies here as new session might have changed them
        proxyList = manager->d_func()->queryProxy(QNetworkProxyQuery(request.url()));
    #endif

    switch (state) {
    case QNetworkReplyImplPrivate::Buffering:
    case QNetworkReplyImplPrivate::Working:
    case QNetworkReplyImplPrivate::Reconnecting:
        // Migrate existing downloads to new network connection.
        migrateBackend();
        break;
    case QNetworkReplyImplPrivate::WaitingForSession:
        // Start waiting requests.
        QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
        break;
    default:
        ;
    }
}
static PyObject *meth_QNetworkProxyFactory_queryProxy(PyObject *sipSelf, PyObject *sipArgs, PyObject *sipKwds)
{
    PyObject *sipParseErr = NULL;
    PyObject *sipOrigSelf = sipSelf;

    {
        const  ::QNetworkProxyQuery& a0def = QNetworkProxyQuery();
        const  ::QNetworkProxyQuery* a0 = &a0def;
         ::QNetworkProxyFactory *sipCpp;

        static const char *sipKwdList[] = {
            sipName_query,
        };

        if (sipParseKwdArgs(&sipParseErr, sipArgs, sipKwds, sipKwdList, NULL, "B|J9", &sipSelf, sipType_QNetworkProxyFactory, &sipCpp, sipType_QNetworkProxyQuery, &a0))
        {
            QList< ::QNetworkProxy>*sipRes;

            if (!sipOrigSelf)
            {
                sipAbstractMethod(sipName_QNetworkProxyFactory, sipName_queryProxy);
                return NULL;
            }

            Py_BEGIN_ALLOW_THREADS
            sipRes = new QList< ::QNetworkProxy>(sipCpp->queryProxy(*a0));
            Py_END_ALLOW_THREADS

            return sipConvertFromNewType(sipRes,sipType_QList_0100QNetworkProxy,NULL);
        }
    }
Exemple #5
0
void tst_QTcpServer::proxyFactory()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy)
        return;

    QFETCH(QList<QNetworkProxy>, proxyList);
    QFETCH(QNetworkProxy, proxyUsed);
    QFETCH(bool, fails);

    MyProxyFactory *factory = new MyProxyFactory;
    factory->toReturn = proxyList;
    QNetworkProxyFactory::setApplicationProxyFactory(factory);

    QTcpServer server;
    bool listenResult = server.listen();

    // Verify that the factory was called properly
    QCOMPARE(factory->callCount, 1);
    QCOMPARE(factory->lastQuery, QNetworkProxyQuery(0, QString(), QNetworkProxyQuery::TcpServer));

    QCOMPARE(listenResult, !fails);
    QCOMPARE(server.errorString().isEmpty(), !fails);

    // note: the following test is not a hard failure.
    // Sometimes, error codes change for the better
    QTEST(int(server.serverError()), "expectedError");
}
Exemple #6
0
    CddbConnection(cddb_disc_t *d) : disc(0) {
        connection = cddb_new();
        if (connection) {
            cddb_cache_disable(connection);
            cddb_set_server_name(connection, Settings::self()->cddbHost().toLatin1().constData());
            cddb_set_server_port(connection, Settings::self()->cddbPort());
            disc=cddb_disc_clone(d);
#ifdef ENABLE_KDE_SUPPORT
            QString proxy=KProtocolManager::proxyFor("http");
            if (!proxy.isEmpty()) {
                QUrl url(proxy);
                cddb_set_http_proxy_server_name(connection, url.host().toLatin1().constData());
                cddb_set_http_proxy_server_port(connection, url.port());
                cddb_http_proxy_enable(connection);
            }
#else
            QUrl url;
            url.setHost(Settings::self()->cddbHost());
            url.setPort(Settings::self()->cddbPort());
            QList<QNetworkProxy> proxies=NetworkProxyFactory::self()->queryProxy(QNetworkProxyQuery(url));

            foreach (const QNetworkProxy &p, proxies) {
                if (QNetworkProxy::HttpProxy==p.type() && 0!=p.port()) {
                    cddb_set_http_proxy_server_name(connection, p.hostName().toLatin1().constData());
                    cddb_set_http_proxy_server_port(connection, p.port());
                    cddb_http_proxy_enable(connection);
                    break;
                }
            }
#endif
        }
    }
Exemple #7
0
void ClientProxy::setCSyncProxy( const QUrl& url, CSYNC *csync_ctx )
{
    /* Store proxy */
    QList<QNetworkProxy> proxies = QNetworkProxyFactory::proxyForQuery(QNetworkProxyQuery(url));
    // We set at least one in Application
    Q_ASSERT(proxies.count() > 0);
    QNetworkProxy proxy = proxies.first();
    if (proxy.type() == QNetworkProxy::NoProxy) {
        qDebug() << "Passing NO proxy to csync for" << url.toString();
    } else {
        qDebug() << "Passing" << proxy.hostName() << "of proxy type " << proxy.type()
                 << " to csync for" << url.toString();
    }

    const char *proxy_type = proxyTypeToCStr(proxy.type());
    const char* proxy_host = proxy.hostName().toUtf8().data();
    int proxy_port         = proxy.port();
    const char *proxy_user = proxy.user().toUtf8().data();
    const char *proxy_pwd  = proxy.password().toUtf8().data();

    csync_set_module_property( csync_ctx, "proxy_type", (void*)proxy_type );
    csync_set_module_property( csync_ctx, "proxy_host", (void*)proxy_host );
    csync_set_module_property( csync_ctx, "proxy_port", (void*)&proxy_port );
    csync_set_module_property( csync_ctx, "proxy_user", (void*)proxy_user );
    csync_set_module_property( csync_ctx, "proxy_pwd",  (void*)proxy_pwd );

}
void SslTlsSocket::delayedStart()
{
    QSslSocket *sock = qobject_cast<QSslSocket *>(d);
    Q_ASSERT(sock);

    switch (m_proxySettings) {
    case Streams::ProxySettings::RespectSystemProxy:
    {
        QNetworkProxy setting;
        QNetworkProxyQuery query = QNetworkProxyQuery(host, port, m_protocolTag, QNetworkProxyQuery::TcpSocket);

        // set to true if a capable setting is found
        bool capableSettingFound = false;

        // set to true if at least one valid setting is found
        bool settingFound = false;

        // FIXME: this static function works particularly slow in Windows
        QList<QNetworkProxy> proxySettingsList = QNetworkProxyFactory::systemProxyForQuery(query);

        /* Proxy Settings are read from the user's environment variables by the above static method.
         * A peculiar case is with *nix systems, where an undefined environment variable is returned as
         * an empty string. Such entries *might* exist in our proxySettingsList, and shouldn't be processed.
         * One good check is to use hostName() of the QNetworkProxy object, and treat the Proxy Setting as invalid if
         * the host name is empty. */
        Q_FOREACH (setting, proxySettingsList) {
            if (!setting.hostName().isEmpty()) {
                settingFound = true;

                // now check whether setting has capabilities
                if (setting.capabilities().testFlag(QNetworkProxy::TunnelingCapability)) {
                    sock->setProxy(setting);
                    capableSettingFound = true;
                    break;
                }
            }
        }

        if (!settingFound || proxySettingsList.isEmpty()) {
            sock->setProxy(QNetworkProxy::NoProxy);
        } else if (!capableSettingFound) {
            emit disconnected(tr("The underlying socket is having troubles when processing connection to %1:%2: %3")
                              .arg(host, QString::number(port), QStringLiteral("Cannot find proxy setting capable of tunneling")));
        }
        break;
    }
    case Streams::ProxySettings::DirectConnect:
        sock->setProxy(QNetworkProxy::NoProxy);
        break;
    }

    if (startEncrypted)
        sock->connectToHostEncrypted(host, port);
    else
        sock->connectToHost(host, port);
}
Exemple #9
0
/*!
    Returns a new QNetworkReply object to handle the operation \a op
    and request \a req. The device \a outgoingData is always 0 for Get and
    Head requests, but is the value passed to post() and put() in
    those operations (the QByteArray variants will pass a QBuffer
    object).

    The default implementation calls QNetworkCookieJar::cookiesForUrl()
    on the cookie jar set with setCookieJar() to obtain the cookies to
    be sent to the remote server.

    The returned object must be in an open state.
*/
QNetworkReply *QNetworkAccessManager::createRequest(QNetworkAccessManager::Operation op,
                                                    const QNetworkRequest &req,
                                                    QIODevice *outgoingData)
{
    Q_D(QNetworkAccessManager);
    QNetworkRequest request = req;
    if (!request.header(QNetworkRequest::ContentLengthHeader).isValid() &&
        outgoingData && !outgoingData->isSequential()) {
        // request has no Content-Length
        // but the data that is outgoing is random-access
        request.setHeader(QNetworkRequest::ContentLengthHeader, outgoingData->size());
    }
    if (d->cookieJar) {
        QList<QNetworkCookie> cookies = d->cookieJar->cookiesForUrl(request.url());
        if (!cookies.isEmpty())
            request.setHeader(QNetworkRequest::CookieHeader, qVariantFromValue(cookies));
    }

    // first step: create the reply
    QUrl url = request.url();
    QNetworkReplyImpl *reply = new QNetworkReplyImpl(this);
    QNetworkReplyImplPrivate *priv = reply->d_func();
    priv->manager = this;

    // second step: fetch cached credentials
    QNetworkAuthenticationCredential *cred = d->fetchCachedCredentials(url);
    if (cred) {
        url.setUserName(cred->user);
        url.setPassword(cred->password);
        priv->urlForLastAuthentication = url;
    }

    // third step: setup the reply
    priv->setup(op, request, outgoingData);
    if (request.attribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork).toInt() !=
        QNetworkRequest::AlwaysNetwork)
        priv->setNetworkCache(d->networkCache);
#ifndef QT_NO_NETWORKPROXY
    QList<QNetworkProxy> proxyList = d->queryProxy(QNetworkProxyQuery(request.url()));
    priv->proxyList = proxyList;
#endif

    // fourth step: find a backend
    priv->backend = d->findBackend(op, request);
    if (priv->backend) {
        priv->backend->setParent(reply);
        priv->backend->reply = priv;
    }

#ifndef QT_NO_OPENSSL
    reply->setSslConfiguration(request.sslConfiguration());
#endif
    return reply;
}
Exemple #10
0
void SystemProxyRunnable::run()
{
    qDebug() << Q_FUNC_INFO << "Starting system proxy lookup";
    QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(_url));

    if (proxies.isEmpty()) {
        emit systemProxyLookedUp(QNetworkProxy(QNetworkProxy::NoProxy));
    } else {
        emit systemProxyLookedUp(proxies.first());
        // FIXME Would we really ever return more?
    }
}
Exemple #11
0
    QList<QNetworkProxy> queryProxy(const QNetworkProxyQuery &query = QNetworkProxyQuery())
    {
        QList<QNetworkProxy> plist;

#if defined(__WINSCW__)
        plist.push_back(QNetworkProxy(QNetworkProxy::HttpProxy,QString("dawebproxy01.americas.nokia.com"), 8080));
#endif
        QUrl proxyUrl = urlFromUserInput(qgetenv("http_proxy"));

        if (proxyUrl.isValid() && !proxyUrl.host().isEmpty()) {
            int proxyPort = (proxyUrl.port() > 0) ? proxyUrl.port() : 8080;
            plist.push_back(QNetworkProxy(QNetworkProxy::HttpProxy, proxyUrl.host(), proxyPort));
        }

        plist.append(systemProxyForQuery(query));
        return plist;
    };
Exemple #12
0
    CddbConnection(cddb_disc_t *d) : disc(0) {
        connection = cddb_new();
        if (connection) {
            cddb_cache_disable(connection);
            cddb_set_server_name(connection, Settings::self()->cddbHost().toLatin1().constData());
            cddb_set_server_port(connection, Settings::self()->cddbPort());
            disc=cddb_disc_clone(d);
            QUrl url;
            url.setHost(Settings::self()->cddbHost());
            url.setPort(Settings::self()->cddbPort());
            QList<QNetworkProxy> proxies=NetworkProxyFactory::self()->queryProxy(QNetworkProxyQuery(url));

            foreach (const QNetworkProxy &p, proxies) {
                if (QNetworkProxy::HttpProxy==p.type() && 0!=p.port()) {
                    cddb_set_http_proxy_server_name(connection, p.hostName().toLatin1().constData());
                    cddb_set_http_proxy_server_port(connection, p.port());
                    cddb_http_proxy_enable(connection);
                    break;
                }
            }
        }
    }
Exemple #13
0
/*!
    Returns a new QNetworkReply object to handle the operation \a op
    and request \a req. The device \a outgoingData is always 0 for Get and
    Head requests, but is the value passed to post() and put() in
    those operations (the QByteArray variants will pass a QBuffer
    object).

    The default implementation calls QNetworkCookieJar::cookiesForUrl()
    on the cookie jar set with setCookieJar() to obtain the cookies to
    be sent to the remote server.

    The returned object must be in an open state.
*/
QNetworkReply *QNetworkAccessManager::createRequest(QNetworkAccessManager::Operation op,
                                                    const QNetworkRequest &req,
                                                    QIODevice *outgoingData)
{
    Q_D(QNetworkAccessManager);

    // fast path for GET on file:// URLs
    // Also if the scheme is empty we consider it a file.
    // The QNetworkAccessFileBackend will right now only be used
    // for PUT or qrc://
    if ((op == QNetworkAccessManager::GetOperation || op == QNetworkAccessManager::HeadOperation)
         && (req.url().scheme() == QLatin1String("file")
             || req.url().scheme().isEmpty())) {
        return new QFileNetworkReply(this, req, op);
    }

#ifndef QT_NO_BEARERMANAGEMENT
    // Return a disabled network reply if network access is disabled.
    // Except if the scheme is empty or file://.
    if (!d->networkAccessible && !(req.url().scheme() == QLatin1String("file") ||
                                      req.url().scheme().isEmpty())) {
        return new QDisabledNetworkReply(this, req, op);
    }

    if (!d->networkSession && (d->initializeSession || !d->networkConfiguration.isEmpty())) {
        QNetworkConfigurationManager manager;
        if (!d->networkConfiguration.isEmpty()) {
            d->createSession(manager.configurationFromIdentifier(d->networkConfiguration));
        } else {
            if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
                d->createSession(manager.defaultConfiguration());
            else
                d->initializeSession = false;
        }
    }

    if (d->networkSession)
        d->networkSession->setSessionProperty(QLatin1String("AutoCloseSessionTimeout"), -1);
#endif

    QNetworkRequest request = req;
    if (!request.header(QNetworkRequest::ContentLengthHeader).isValid() &&
        outgoingData && !outgoingData->isSequential()) {
        // request has no Content-Length
        // but the data that is outgoing is random-access
        request.setHeader(QNetworkRequest::ContentLengthHeader, outgoingData->size());
    }
    if (d->cookieJar) {
        QList<QNetworkCookie> cookies = d->cookieJar->cookiesForUrl(request.url());
        if (!cookies.isEmpty())
            request.setHeader(QNetworkRequest::CookieHeader, qVariantFromValue(cookies));
    }

    // first step: create the reply
    QUrl url = request.url();
    QNetworkReplyImpl *reply = new QNetworkReplyImpl(this);
#ifndef QT_NO_BEARERMANAGEMENT
    if (req.url().scheme() != QLatin1String("file") && !req.url().scheme().isEmpty()) {
        connect(this, SIGNAL(networkSessionConnected()),
                reply, SLOT(_q_networkSessionConnected()));
    }
#endif
    QNetworkReplyImplPrivate *priv = reply->d_func();
    priv->manager = this;

    // second step: fetch cached credentials
    QNetworkAuthenticationCredential *cred = d->fetchCachedCredentials(url);
    if (cred) {
        url.setUserName(cred->user);
        url.setPassword(cred->password);
        priv->urlForLastAuthentication = url;
    }

    // third step: find a backend
    priv->backend = d->findBackend(op, request);

#ifndef QT_NO_NETWORKPROXY
    QList<QNetworkProxy> proxyList = d->queryProxy(QNetworkProxyQuery(request.url()));
    priv->proxyList = proxyList;
#endif
    if (priv->backend) {
        priv->backend->setParent(reply);
        priv->backend->reply = priv;
    }
    // fourth step: setup the reply
    priv->setup(op, request, outgoingData);

#ifndef QT_NO_OPENSSL
    reply->setSslConfiguration(request.sslConfiguration());
#endif
    return reply;
}
Exemple #14
0
int main(int argc, char *argv[])
{
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8"));
	QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
	
	julyTranslator=new JulyTranslator;
	appDataDir_=new QByteArray();
	appVerIsBeta_=new bool(false);
	appVerStr_=new QByteArray("1.0707");
	appVerReal_=new double(appVerStr.toDouble());
	if(appVerStr.size()>4)
	{ 
		appVerStr.insert(4,".");
		if(appVerStr.at(appVerStr.size()-1)!='0')appVerIsBeta=true;
	}
	appVerLastReal_=new double(appVerReal);
	currencyBStr_=new QByteArray("USD");
	currencyBStrLow_=new QByteArray("usd");
	currencyBSign_=new QByteArray("USD");
	validKeySign_=new bool(false);
	currencyASign_=new QByteArray("BTC");
	currencyAStr_=new QByteArray("BTC");
	currencyAStrLow_=new QByteArray("btc");
	currencyRequest_=new QByteArray("BTCUSD");
	defaultLangFile_=new QString();pickDefaultLangFile();
	currencySignMap=new QMap<QByteArray,QByteArray>;
	currencyNamesMap=new QMap<QByteArray,QByteArray>;
	dateTimeFormat_=new QString(QLocale().dateTimeFormat(QLocale::ShortFormat));
	timeFormat_=new QString(QLocale().timeFormat(QLocale::ShortFormat));
	exchangeName_=new QString("Mt.Gox");
	btcDecimals_=new int(8);
	usdDecimals_=new int(5);
	priceDecimals_=new int(5);

	minTradePrice_=new double(0.01);
	minTradeVolume_=new double(0.01);
	currentTimeStamp_=new qint32(QDateTime::currentDateTime().toTime_t());
	httpRequestInterval_=new int(400);
	httpRequestTimeout_=new int(5);

	QString globalStyleSheet="QGroupBox {background: rgba(255,255,255,190); border: 1px solid gray;border-radius: 3px;margin-top: 7px;} QGroupBox:title {background: qradialgradient(cx: 0.5, cy: 0.5, fx: 0.5, fy: 0.5, radius: 0.7, stop: 0 #fff, stop: 1 transparent); border-radius: 2px; padding: 1 4px; top: -7; left: 7px;} QLabel {color: black;} QDoubleSpinBox {background: white;} QTextEdit {background: white;} QPlainTextEdit {background: white;} QCheckBox {color: black;} QLineEdit {color: black; background: white; border: 1px solid gray;}";

#ifdef Q_OS_WIN
	if(QFile::exists("./QtBitcoinTrader"))
	{
		appDataDir="./QtBitcoinTrader/";
		QDir().mkpath(appDataDir+"Language");
		if(!QFile::exists(appDataDir+"Language"))appDataDir.clear();
	}
	if(appDataDir.isEmpty())
	{
	appDataDir=QDesktopServices::storageLocation(QDesktopServices::DataLocation).replace("\\","/").toAscii()+"/QtBitcoinTrader/";
	if(!QFile::exists(appDataDir))QDir().mkpath(appDataDir);
	}
#else
	appDataDir=QDesktopServices::storageLocation(QDesktopServices::HomeLocation).toAscii()+"/.config/QtBitcoinTrader/";
	if(!QFile::exists(appDataDir))QDir().mkpath(appDataDir);
#endif
	
    if(argc>1)
	{
		QApplication a(argc,argv);
        if(a.arguments().last().startsWith("/checkupdate"))
		{
#ifndef Q_OS_WIN
			a.setStyle(new QPlastiqueStyle);
#endif
			a.setStyleSheet(globalStyleSheet);

			QSettings settings(appDataDir+"/Settings.set",QSettings::IniFormat);
			QString langFile=settings.value("LanguageFile","").toString();
			if(langFile.isEmpty()||!langFile.isEmpty()&&!QFile::exists(langFile))langFile=defaultLangFile;
			julyTranslator->loadFromFile(langFile);

			UpdaterDialog updater(a.arguments().last()!="/checkupdate");
			return a.exec();
		}
	}

	QApplication a(argc,argv);
#ifndef Q_OS_WIN
	a.setStyle(new QPlastiqueStyle);
#endif

#ifdef  Q_OS_WIN
	if(QFile::exists(a.applicationFilePath()+".upd"))QFile::remove(a.applicationFilePath()+".upd");
	if(QFile::exists(a.applicationFilePath()+".bkp"))QFile::remove(a.applicationFilePath()+".bkp");
#endif

#ifdef  Q_OS_MAC
	if(QFile::exists(a.applicationFilePath()+".upd"))QFile::remove(a.applicationFilePath()+".upd");
	if(QFile::exists(a.applicationFilePath()+".bkp"))QFile::remove(a.applicationFilePath()+".bkp");
#endif

	a.setWindowIcon(QIcon(":/Resources/QtBitcoinTrader.png"));
	QFile *lockFile=0;

	{
		QNetworkProxy proxy;
		QList<QNetworkProxy> proxyList=QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(QUrl("https://")));
		if(proxyList.count())proxy=proxyList.first();
		QNetworkProxy::setApplicationProxy(proxy);

	logEnabled_=new bool(false);

	a.setStyleSheet(globalStyleSheet);

	logFileName_=new QString("QtBitcoinTrader.log");
	iniFileName_=new QString("QtBitcoinTrader.ini");

	restKey_=new QByteArray;
	restSign_=new QByteArray;
	{
		QFile currencyFile("://Resources/Currencies.map");
		currencyFile.open(QIODevice::ReadOnly);
		QStringList currencyList=QString(currencyFile.readAll().replace("\r","")).split("\n");
		currencyFile.close();
		for(int n=0;n<currencyList.count();n++)
		{
			QStringList currencyName=currencyList.at(n).split("=");
			if(currencyName.count()!=3)continue;
			currencyNamesMap->insert(currencyName.at(0).toAscii(),currencyName.at(1).toAscii());
			currencySignMap->insert(currencyName.at(0).toAscii(),currencyName.at(2).toAscii());
		}
		if(!QFile::exists(appDataDir+"Language"))QDir().mkpath(appDataDir+"Language");
		QSettings settings(appDataDir+"/Settings.set",QSettings::IniFormat);
		QString langFile=settings.value("LanguageFile","").toString();
		appVerLastReal=settings.value("Version",1.0).toDouble();
		settings.setValue("Version",appVerReal);
		if(langFile.isEmpty()||!langFile.isEmpty()&&!QFile::exists(langFile))langFile=defaultLangFile;
			julyTranslator->loadFromFile(langFile);
	}

	bool tryDecrypt=true;
	bool showNewPasswordDialog=false;
	while(tryDecrypt)
	{
		QString tryPassword;
		restKey.clear();
		restSign.clear();

		if(QDir(appDataDir,"*.ini").entryList().isEmpty()||showNewPasswordDialog)
		{
			NewPasswordDialog newPassword;
			if(newPassword.exec()==QDialog::Accepted)
			{
			tryPassword=newPassword.getPassword();
			newPassword.updateIniFileName();
			restKey=newPassword.getRestKey().toAscii();
			QSettings settings(iniFileName,QSettings::IniFormat);
			settings.setValue("ExchangeId",newPassword.getExchangeId());
			QByteArray cryptedData;
			if(newPassword.getExchangeId()==0)
			{
			restSign=QByteArray::fromBase64(newPassword.getRestSign().toAscii());
			cryptedData=JulyAES256::encrypt("Qt Bitcoin Trader\r\n"+restKey+"\r\n"+restSign.toBase64(),tryPassword.toAscii());
			}
			else
			if(newPassword.getExchangeId()==1)
			{
				restSign=newPassword.getRestSign().toAscii();
				cryptedData=JulyAES256::encrypt("Qt Bitcoin Trader\r\n"+restKey+"\r\n"+restSign.toBase64(),tryPassword.toAscii());
			}
			settings.setValue("CryptedData",QString(cryptedData.toBase64()));
			settings.setValue("ProfileName",newPassword.selectedProfileName());
			settings.remove("RestSign");
			settings.remove("RestKey");
			settings.sync();

			showNewPasswordDialog=false;
			}
		}
			PasswordDialog enterPassword;
			if(enterPassword.exec()==QDialog::Rejected)return 0;
			if(enterPassword.resetData)
			{
				if(QFile::exists(enterPassword.getIniFilePath()))
					QFile::remove(enterPassword.getIniFilePath());
				continue;
			}
			if(enterPassword.newProfile){showNewPasswordDialog=true;continue;}
			tryPassword=enterPassword.getPassword();

		if(!tryPassword.isEmpty())
		{
			iniFileName=enterPassword.getIniFilePath();
			bool profileLocked=enterPassword.isProfileLocked(iniFileName);
			if(profileLocked)
			{
				QMessageBox msgBox(0);
				msgBox.setIcon(QMessageBox::Question);
				msgBox.setWindowTitle("Qt Bitcoin Trader");
				msgBox.setText(julyTr("THIS_PROFILE_ALREADY_USED","This profile is already used by another instance.<br>API does not allow to run two instances with same key sign pair.<br>Please create new profile if you want to use two instances."));
#ifdef Q_OS_WIN
				msgBox.setStandardButtons(QMessageBox::Ok);
				msgBox.setDefaultButton(QMessageBox::Ok);
				msgBox.exec();
#else
				msgBox.setStandardButtons(QMessageBox::Ignore|QMessageBox::Ok);
				msgBox.setDefaultButton(QMessageBox::Ok);
				if(msgBox.exec()==QMessageBox::Ignore)profileLocked=false;
#endif
				if(profileLocked)tryPassword.clear();
			}
			if(!profileLocked)
			{
				QSettings settings(iniFileName,QSettings::IniFormat);
				QStringList decryptedList=QString(JulyAES256::decrypt(QByteArray::fromBase64(settings.value("CryptedData","").toString().toAscii()),tryPassword.toAscii())).split("\r\n");

				if(decryptedList.count()==3&&decryptedList.first()=="Qt Bitcoin Trader")
				{
					restKey=decryptedList.at(1).toAscii();
					restSign=QByteArray::fromBase64(decryptedList.last().toAscii());
                    tryDecrypt=false;
					lockFile=new QFile(enterPassword.lockFilePath(iniFileName));
                    lockFile->open(QIODevice::WriteOnly|QIODevice::Truncate);
					lockFile->write("Qt Bitcoin Trader Lock File");
				}
			}
		}
	}

	QSettings settings(iniFileName,QSettings::IniFormat);
	isLogEnabled=settings.value("LogEnabled",false).toBool();
	settings.setValue("LogEnabled",isLogEnabled);
	currencyASign=currencySignMap->value("BTC","BTC");
	currencyBStr=settings.value("Currency","USD").toString().toAscii();
	currencyBSign=currencySignMap->value(currencyBStr,"$");

	if(isLogEnabled)logThread=new LogThread;

	mainWindow_=new QtBitcoinTrader;
	QObject::connect(mainWindow_,SIGNAL(quit()),&a,SLOT(quit()));
	}
	mainWindow.loadUiSettings();
	a.exec();
	if(lockFile)
	{
		lockFile->close();
		lockFile->remove();
		delete lockFile;
	}
	return 0;
}
Exemple #15
0
 QNetworkProxy applicationProxy()
 {
     return proxyForQuery(QNetworkProxyQuery()).first();
 }
Exemple #16
0
 inline void clear()
 {
     callCount = 0;
     toReturn = QList<QNetworkProxy>() << QNetworkProxy::DefaultProxy;
     lastQuery = QNetworkProxyQuery();
 }
void RemoteDatabase::reloadSettings()
{
    // Load all configured client certificates
    m_clientCertFiles.clear();
    auto client_certs = Settings::getValue("remote", "client_certificates").toStringList();
    for(const QString& path : client_certs)
    {
        QFile file(path);
        file.open(QFile::ReadOnly);
        QSslCertificate cert(&file);
        file.close();
        m_clientCertFiles.insert({path, cert});
    }

    // Always add the default certificate for anonymous access to dbhub.io
    {
        QFile file(":/user_certs/public.cert.pem");
        file.open(QFile::ReadOnly);
        QSslCertificate cert(&file);
        file.close();
        m_clientCertFiles.insert({":/user_certs/public.cert.pem", cert});
    }

    // Configure proxy to use
    {
        QString type = Settings::getValue("proxy", "type").toString();

        QNetworkProxy proxy;
        if(type == "system")
        {
            // For system settings we have to get the system-wide proxy and use that

            // Get list of proxies for accessing dbhub.io via HTTPS and use the first one
            auto list = QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(QUrl("https://db4s.dbhub.io/")));
            proxy = list.front();
        } else {
            // For any other type we have to set up our own proxy configuration

            // Retrieve the required settings
            QString host = Settings::getValue("proxy", "host").toString();
            unsigned short port = static_cast<unsigned short>(Settings::getValue("proxy", "port").toUInt());
            bool authentication = Settings::getValue("proxy", "authentication").toBool();

            if(type == "http")
                proxy.setType(QNetworkProxy::HttpProxy);
            else if(type == "socks5")
                proxy.setType(QNetworkProxy::Socks5Proxy);
            else
                proxy.setType(QNetworkProxy::NoProxy);

            proxy.setHostName(host);
            proxy.setPort(port);

            // Only set authentication details when authentication is required
            if(authentication)
            {
                QString user = Settings::getValue("proxy", "user").toString();
                QString password = Settings::getValue("proxy", "password").toString();

                proxy.setUser(user);
                proxy.setPassword(password);
            }
        }

        // Start using the new proxy configuration
        QNetworkProxy::setApplicationProxy(proxy);
    }
}