示例#1
0
void CMyMainWindow::ReadAndApplyProxySettings(){
	// Read current proxy settings
    netstatus_proxy_details_t details;
    memset(&details, 0, sizeof(details));
    if (netstatus_get_proxy_details(&details) == BPS_FAILURE) {
    	qDebug() << QString("CMyMainWindow::ReadAndApplyProxySettings(): netstatus_get_proxy_details() failed");
        return;
    }
    QString host = details.http_proxy_host;
    QString port = QString::number(details.http_proxy_port);
    QString user = details.http_proxy_login_user;
    QString password = details.http_proxy_login_password;
    netstatus_free_proxy_details(&details);

    QDir SshDir(QString("data"));
    QDir SshDir1(QString("data/.ssh"));
    if (!SshDir1.exists())
    	if (!SshDir.mkdir(".ssh"))
    		qDebug() << "CMyMainWindow::ReadAndApplyProxySettings(): Can't create data/.ssh";

	QSettings settings;
	int nProxyOn = settings.value("HttpProxyOn").toInt();
	if (nProxyOn && !host.isEmpty()){
		// Proxy should be turned on

	    QString proxycommand;
		if (user.isEmpty()){
			proxycommand = "\tProxyCommand corkscrew " + host + " " + port + " %h %p\n";
			QFile fileSshProxyAuth(SSH_PROXY_AUTH_FNAME);
			if (fileSshProxyAuth.exists())
				fileSshProxyAuth.remove();
		}else{
		    // Create auth file
			QFile fileSshProxyAuth(SSH_PROXY_AUTH_FNAME);
		    if (fileSshProxyAuth.open(QIODevice::WriteOnly)){
		    	QString line = user + ":" + password + "\n";
		    	fileSshProxyAuth.write(line.toAscii());
		    	fileSshProxyAuth.close();
		    	fileSshProxyAuth.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
		    	proxycommand = "\tProxyCommand corkscrew " + host + " " + port + " %h %p ~/.ssh/myauth\n";
		    }else{
				qDebug() << QString("CMyMainWindow::ReadAndApplyProxySettings(): can't open ") + QString(SSH_PROXY_AUTH_FNAME) + QString(" for writing");
				proxycommand = "\tProxyCommand corkscrew " + host + " " + port + " %h %p\n";
		    }
		}
		QFile fileSshConfig(SSH_CONFIG_FNAME);
		if (fileSshConfig.exists()){
			// file does exist
			if (!fileSshConfig.open(QIODevice::ReadOnly)){
				qDebug() << QString("CMyMainWindow::ReadAndApplyProxySettings(): can't open ") + QString(SSH_CONFIG_FNAME) + QString(" for reading");
				return;
			}
			QFile fileSshConfigTmp(SSH_CONFIG_FNAME_TMP);
			if (!fileSshConfigTmp.open(QIODevice::WriteOnly)){
				qDebug() << QString("CMyMainWindow::ReadAndApplyProxySettings(): can't open ") + QString(SSH_CONFIG_FNAME_TMP) + QString(" for writing");
				fileSshConfig.close();
				return;
			}
			bool bHostAllFound = false;
			bool bProxyCommandFound = false;
			QTextStream in(&fileSshConfig);
		    while (!in.atEnd()) {
		    	QString line = in.readLine();
		    	if (bHostAllFound){
		    		// We already saw line "Host *", searching for "ProxyCommand"
		    		if (!bProxyCommandFound){
		    			if (line.contains(QString("ProxyCommand"), Qt::CaseInsensitive)){
		    				bProxyCommandFound = true;
		    				fileSshConfigTmp.write(proxycommand.toAscii());
		    			}else{
		    				if (line.contains(QString("Host"), Qt::CaseInsensitive)){
		    					// Next "Host" block we need to write our proxy before
			    				fileSshConfigTmp.write(proxycommand.toAscii());
			    				bProxyCommandFound = true;
		    				}
		    				line += '\n';
		    				fileSshConfigTmp.write(line.toAscii());
		    			}
		    		}else{
		    			line += '\n';
		    			fileSshConfigTmp.write(line.toAscii());
		    		}
		    	}else{
		    		// "Host *" is not found yet
			    	if (line.contains(QString("Host *"), Qt::CaseInsensitive))
			    		bHostAllFound = true;
		    		line += '\n';
		    		fileSshConfigTmp.write(line.toAscii());
		    	}
		    }
	    	if (!bHostAllFound){
				fileSshConfigTmp.write("Host *\n");
				fileSshConfigTmp.write(proxycommand.toAscii());
	    	}else{
	    		if (!bProxyCommandFound)
					fileSshConfigTmp.write(proxycommand.toAscii());
	    	}
		    fileSshConfig.close();
		    fileSshConfig.remove();
		    fileSshConfigTmp.close();
		    fileSshConfigTmp.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
		    fileSshConfigTmp.rename(SSH_CONFIG_FNAME);

		    return;
		}else{
			// file does not exist, let's create it
			if (!fileSshConfig.open(QIODevice::WriteOnly)){
				qDebug() << QString("CMyMainWindow::ReadAndApplyProxySettings(): can't open ") + QString(SSH_CONFIG_FNAME) + QString(" for writing");
				return;
			}
			fileSshConfig.write("Host *\n");
			fileSshConfig.write(proxycommand.toAscii());
			fileSshConfig.close();
			fileSshConfig.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
		}
	}else{
		// Proxy should be turned off
		QFile fileSshProxyAuth(SSH_PROXY_AUTH_FNAME);
		if (fileSshProxyAuth.exists())
			fileSshProxyAuth.remove();

		QFile fileSshConfig(SSH_CONFIG_FNAME);
		if (fileSshConfig.exists()){
			// file does exist, let's make sure that there is no proxy for Host *
			if (!fileSshConfig.open(QIODevice::ReadOnly)){
				qDebug() << QString("CMyMainWindow::ReadAndApplyProxySettings(): can't open ") + QString(SSH_CONFIG_FNAME) + QString(" for reading");
				return;
			}
			QFile fileSshConfigTmp(SSH_CONFIG_FNAME_TMP);
			if (!fileSshConfigTmp.open(QIODevice::WriteOnly)){
				qDebug() << QString("CMyMainWindow::ReadAndApplyProxySettings(): can't open ") + QString(SSH_CONFIG_FNAME_TMP) + QString(" for writing");
				fileSshConfig.close();
				return;
			}
			QTextStream in(&fileSshConfig);
		    while (!in.atEnd()) {
		    	QString line = in.readLine();
		    	if (!line.contains(QString("ProxyCommand"), Qt::CaseInsensitive)){
		    		// Write everything except ProxyCommand into new file
		    		line += '\n';
		    		fileSshConfigTmp.write(line.toAscii());
		    	}
		    }
		    fileSshConfig.close();
		    fileSshConfig.remove();
		    fileSshConfigTmp.close();
		    fileSshConfigTmp.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
		    fileSshConfigTmp.rename(SSH_CONFIG_FNAME);

		    return;
		}else{
			// file does not exist, so nothing to do
			return;

		}
	}
}
QT_BEGIN_NAMESPACE

QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery &query)
{
    QNetworkProxy proxy;

    if (query.queryType() != QNetworkProxyQuery::UrlRequest) {
        qWarning("Unsupported query type: %d", query.queryType());
        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
    }

    QUrl url  = query.url();

    if (!url.isValid()) {
        qWarning("Invalid URL: %s", qPrintable(url.toString()));
        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
    }

    netstatus_proxy_details_t details;
    memset(&details, 0, sizeof(netstatus_proxy_details_t));

#if BPS_VERSION >= 3001001

    QByteArray bUrl(url.toEncoded());
    QString sInterface(query.networkConfiguration().name());
    QByteArray bInterface;
    if (!sInterface.isEmpty()) {
        if (query.networkConfiguration().type() != QNetworkConfiguration::InternetAccessPoint) {
            qWarning("Unsupported configuration type: %d", query.networkConfiguration().type());
            return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
        }
        bInterface = sInterface.toUtf8();
    }

    if (netstatus_get_proxy_details_for_url(bUrl.constData(), (bInterface.isEmpty() ? NULL : bInterface.constData()), &details) != BPS_SUCCESS) {
        qWarning("netstatus_get_proxy_details_for_url failed! errno: %d", errno);
        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
    }

#else

    if (netstatus_get_proxy_details(&details) != BPS_SUCCESS) {
        qWarning("netstatus_get_proxy_details failed! errno: %d", errno);
        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
    }

#endif

    if (details.http_proxy_host == NULL) { // No proxy
        netstatus_free_proxy_details(&details);
        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
    }

    QString protocol = query.protocolTag();
    if (protocol.startsWith(QLatin1String("http"), Qt::CaseInsensitive)) { // http, https
        proxy.setType((QNetworkProxy::HttpProxy));
    } else if (protocol == QLatin1String("ftp")) {
        proxy.setType(QNetworkProxy::FtpCachingProxy);
    } else { // assume http proxy
        qDebug("Proxy type: %s assumed to be http proxy", qPrintable(protocol));
        proxy.setType((QNetworkProxy::HttpProxy));
    }

    // Set host
    // Note: ftp and https proxy type fields *are* obsolete.
    // The user interface allows only one host/port which gets duplicated
    // to all proxy type fields.
    proxy.setHostName(QString::fromUtf8(details.http_proxy_host));

    // Set port
    proxy.setPort(details.http_proxy_port);

    // Set username
    if (details.http_proxy_login_user)
        proxy.setUser(QString::fromUtf8(details.http_proxy_login_user));

    // Set password
    if (details.http_proxy_login_password)
        proxy.setPassword(QString::fromUtf8(details.http_proxy_login_password));

    netstatus_free_proxy_details(&details);

    return QList<QNetworkProxy>() << proxy;
}
void CurlConnectThread::run()
{
	const char *httpsURL = "https://ca.yahoo.com/?p=us";

    netstatus_proxy_details_t details;
    memset(&details, 0, sizeof(details));
    CURL *curl_handle = NULL;
    bool proxyWasNotRequired = false;

    if (bps_initialize() == BPS_SUCCESS) {

		if (netstatus_get_proxy_details(&details) == BPS_SUCCESS) {

		    // init the curl session
		    curl_global_init(CURL_GLOBAL_ALL);
		    curl_handle = curl_easy_init();

		    if (curl_handle) {

				/* set URL to get */
				curl_easy_setopt(curl_handle, CURLOPT_URL, httpsURL);

				/* if proxy is required, then set proxy */
				if (details.http_proxy_host == NULL) {
					proxyWasNotRequired = true;
					qDebug() << (QString("No proxy required!\n"));
				} else {
					curl_easy_setopt(curl_handle, CURLOPT_PROXY, details.http_proxy_host);
					qDebug() << (QString("proxy host: ").append(details.http_proxy_host).append("\n"));

					/* if we have a valid port number then let libcurl know what it is */
					if (details.http_proxy_port != 0) {
						curl_easy_setopt(curl_handle, CURLOPT_PROXYPORT, (long)details.http_proxy_port);
						qDebug() << (QString("proxy port: ").append(QString::number(details.http_proxy_port)).append("\n"));
					}
				}

				/* if proxy user name is available, then set the user name */
				if (details.http_proxy_login_user != NULL) {
					curl_easy_setopt(curl_handle, CURLOPT_PROXYUSERNAME, details.http_proxy_login_user);
					qDebug() << (QString("proxy username: "******"\n"));
				}
				/* if proxy password is available, then set the password */
				if (details.http_proxy_login_password != NULL) {
					curl_easy_setopt(curl_handle, CURLOPT_PROXYPASSWORD, details.http_proxy_login_password);
					qDebug() << (QString("proxy PASSWORD: "******"\n"));
				}

				/* no progress meter, please */
				curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);

				/* send all data to this function  */
				curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);

				/*
				 * Notice here that if you want the actual data sent anywhere else but
				 * stdout, you should consider using the CURLOPT_WRITEDATA option.
				 */

			    BESSafeTcp::consoleLog("ready to connect\n");

				// get it!
				curl_easy_perform(curl_handle);

			    BESSafeTcp::consoleLog("retrieved data\n");

				/* Step 5: Tear Down and Clean Up
				 * ==============================
				 */

				// cleanup curl stuff
				curl_easy_cleanup(curl_handle);

		    }


		    // cleanup netstatus proxy details
		    netstatus_free_proxy_details(&details);
		}

	    // cleanup bps stuff
	    bps_shutdown();

    }
}