void OpenconnectSettingWidget::writeConfig()
{
    Q_D(OpenconnectSettingWidget);

    d->setting->setServiceType(QLatin1String(NM_DBUS_SERVICE_OPENCONNECT));

    QStringMap data;
    QStringMap secretData;

    data.insert(QLatin1String(NM_OPENCONNECT_KEY_GATEWAY), d->ui.leGateway->text().toUtf8());
    if (!d->ui.leCaCertificate->url().isEmpty())
        data.insert(QLatin1String(NM_OPENCONNECT_KEY_CACERT), d->ui.leCaCertificate->url().path());
    if (!d->ui.leProxy->text().isEmpty())
        data.insert(QLatin1String(NM_OPENCONNECT_KEY_PROXY), d->ui.leProxy->text().toUtf8());
    data.insert(QLatin1String(NM_OPENCONNECT_KEY_CSD_ENABLE), d->ui.chkAllowTrojan->isChecked() ? "yes" : "no");
    if (!d->ui.leCsdWrapperScript->url().isEmpty())
        data.insert(QLatin1String(NM_OPENCONNECT_KEY_CSD_WRAPPER), d->ui.leCsdWrapperScript->url().path());
    if (!d->ui.leUserCert->url().isEmpty())
        data.insert(QLatin1String(NM_OPENCONNECT_KEY_USERCERT), d->ui.leUserCert->url().path());
    if (!d->ui.leUserPrivateKey->url().isEmpty())
        data.insert(QLatin1String(NM_OPENCONNECT_KEY_PRIVKEY), d->ui.leUserPrivateKey->url().path());
    data.insert(QLatin1String(NM_OPENCONNECT_KEY_PEM_PASSPHRASE_FSID), d->ui.chkUseFsid->isChecked() ? "yes" : "no");

    /* These are different for every login session, and should not be stored */
    data.insert(QLatin1String(NM_OPENCONNECT_KEY_COOKIE"-flags"), QString::number(Knm::Setting::NotSaved));
    data.insert(QLatin1String(NM_OPENCONNECT_KEY_GWCERT"-flags"), QString::number(Knm::Setting::NotSaved));
    data.insert(QLatin1String(NM_OPENCONNECT_KEY_GATEWAY"-flags"), QString::number(Knm::Setting::NotSaved));

    d->setting->setData(data);

    //VpnSecrets empty so far, they will be acquired by the auth dialog
    d->setting->setVpnSecrets(secretData);
}
uint VpncSettingWidget::handleOnePasswordType(const QComboBox * combo, const QString & key, QStringMap & data)
{
    uint type = combo->currentIndex();
    switch (type) {
    case VpncSettingWidgetPrivate::EnumPasswordStorage::AlwaysAsk:
        data.insert(key, QString::number(Knm::Setting::NotSaved));
        break;
    case VpncSettingWidgetPrivate::EnumPasswordStorage::Save:
        data.insert(key, QString::number(Knm::Setting::AgentOwned));
        break;
    case VpncSettingWidgetPrivate::EnumPasswordStorage::NotRequired:
        data.insert(key, QString::number(Knm::Setting::NotRequired));
        break;
    }
    return type;
}
QStringMap AbstractWebApplication::parseCookie(const Http::Request &request) const
{
    // [rfc6265] 4.2.1. Syntax
    QStringMap ret;
    const QString cookieStr = request.headers.value(QLatin1String("cookie"));
    const QVector<QStringRef> cookies = cookieStr.splitRef(';', QString::SkipEmptyParts);

    for (const auto &cookie : cookies) {
        const int idx = cookie.indexOf('=');
        if (idx < 0)
            continue;

        const QString name = cookie.left(idx).trimmed().toString();
        const QString value = Utils::String::unquote(cookie.mid(idx + 1).trimmed())
                                  .toString();
        ret.insert(name, value);
    }
    return ret;
}
Beispiel #4
0
void SSDP::ProcessData( MSocketDevice *pSocket )
{
    QByteArray buffer;
    long nBytes = 0;

    while ((nBytes = pSocket->bytesAvailable()) > 0)
    {
        buffer.resize(nBytes);

        long nRead = 0;
        do
        {
            long ret = pSocket->readBlock( buffer.data() + nRead, nBytes - nRead );
            if (ret < 0)
            {
                LOG(VB_GENERAL, LOG_ERR, QString("Socket readBlock error %1")
                    .arg(pSocket->error()));
                buffer.clear();
                break;
            }

            nRead += ret;

            if (0 == ret)
            {
                LOG(VB_SOCKET, LOG_WARNING,
                    QString("%1 bytes reported available, "
                            "but only %2 bytes read.")
                    .arg(nBytes).arg(nRead));
                nBytes = nRead;
                buffer.resize(nBytes);
                break;
            }
        }
        while (nRead < nBytes);

        if (buffer.isEmpty())
            continue;

        QHostAddress  peerAddress = pSocket->peerAddress();
        quint16       peerPort    = pSocket->peerPort   ();

        // ------------------------------------------------------------------
        QString     str          = QString(buffer.constData());
        QStringList lines        = str.split("\r\n", QString::SkipEmptyParts);
        QString     sRequestLine = lines.size() ? lines[0] : "";

        lines.pop_front();

        // ------------------------------------------------------------------
        // Parse request Type
        // ------------------------------------------------------------------

        LOG(VB_UPNP, LOG_DEBUG, QString("SSDP::ProcessData - requestLine: %1")
                .arg(sRequestLine));

        SSDPRequestType eType = ProcessRequestLine( sRequestLine );

        // ------------------------------------------------------------------
        // Read Headers into map
        // ------------------------------------------------------------------

        QStringMap  headers;

        for ( QStringList::Iterator it = lines.begin();
                                    it != lines.end(); ++it ) 
        {
            QString sLine  = *it;
            QString sName  = sLine.section( ':', 0, 0 ).trimmed();
            QString sValue = sLine.section( ':', 1 );

            sValue.truncate( sValue.length() );  //-2

            if ((sName.length() != 0) && (sValue.length() !=0))
                headers.insert( sName.toLower(), sValue.trimmed() );
        }

#if 0
        pSocket->SetDestAddress( peerAddress, peerPort );
#endif

        // --------------------------------------------------------------
        // See if this is a valid request
        // --------------------------------------------------------------

        switch( eType )
        {
            case SSDP_MSearch:
            {
                // ----------------------------------------------------------
                // If we haven't enabled notifications yet, then we don't 
                // want to answer search requests.
                // ----------------------------------------------------------

                if (m_pNotifyTask != NULL)
                    ProcessSearchRequest( headers, peerAddress, peerPort ); 

                break;
            }

            case SSDP_MSearchResp:
                ProcessSearchResponse( headers); 
                break;

            case SSDP_Notify:
                ProcessNotify( headers ); 
                break;

            case SSDP_Unknown:
            default:
                LOG(VB_UPNP, LOG_ERR,
                    "SSPD::ProcessData - Unknown request Type.");
                break;
        }
    }
}
void NovellVpnSettingWidget::writeX509Auth(QStringMap & data, QStringMap & secretData)
{
    data.insert(QLatin1String(NM_NOVELLVPN_KEY_AUTHTYPE), QLatin1String(NM_NOVELLVPN_CONTYPE_X509_STRING));
    data.insert(NM_NOVELLVPN_KEY_CERTIFICATE, d->ui.x509Cert->url().path());
    secretData.insert(QLatin1String(NM_NOVELLVPN_KEY_CERT_PWD), d->ui.x509CertPass->text());
}
void NovellVpnSettingWidget::writeConfig()
{
    kDebug();

    d->setting->setServiceType(QLatin1String(NM_DBUS_SERVICE_NOVELLVPN));

    QStringMap data;
    QStringMap secretData;

    // required settings
    data.insert(NM_NOVELLVPN_KEY_GATEWAY, d->ui.leGateway->text());

    if (d->ui.cmbGwType->currentIndex() == 0) {
        data.insert(QLatin1String(NM_NOVELLVPN_KEY_GWTYPE), QLatin1String(NM_NOVELLVPN_GWTYPE_NORTEL_STRING));

        if (d->ui.cmbAuthType->currentIndex() == 0) {
            data.insert(QLatin1String(NM_NOVELLVPN_KEY_AUTHTYPE), QLatin1String(NM_NOVELLVPN_CONTYPE_GROUPAUTH_STRING));

            data.insert(QLatin1String(NM_NOVELLVPN_KEY_USER_NAME), d->ui.leUserName->text());
            data.insert(QLatin1String(NM_NOVELLVPN_KEY_GROUP_NAME), d->ui.leGroupName->text());
            secretData.insert(QLatin1String(NM_NOVELLVPN_KEY_USER_PWD), d->ui.leUserPass->text());
            secretData.insert(QLatin1String(NM_NOVELLVPN_KEY_GRP_PWD), d->ui.leGroupPass->text());
        } else {
            writeX509Auth(data, secretData);
        }
    } else {
        data.insert(QLatin1String(NM_NOVELLVPN_KEY_GWTYPE), QLatin1String(NM_NOVELLVPN_GWTYPE_STDGW_STRING));
        writeX509Auth(data, secretData);
    }

    // advanced dialog
    data.insert(QLatin1String(NM_NOVELLVPN_KEY_DHGROUP),
            (d->advUi.rbDh1->isChecked()
             ? QString::number(DHGROUP_DH1)
             : QString::number(DHGROUP_DH2)));

    if (d->advUi.rbPfOff->isChecked()) {
        data.insert(QLatin1String(NM_NOVELLVPN_KEY_PFSGROUP), QString::number(PFSGROUP_OFF));
    } else if (d->advUi.rbPf1->isChecked()) {
        data.insert(QLatin1String(NM_NOVELLVPN_KEY_PFSGROUP), QString::number(PFSGROUP_PFS1));
    } else {
        data.insert(QLatin1String(NM_NOVELLVPN_KEY_PFSGROUP), QString::number(PFSGROUP_PFS2));
    }

    data.insert(QLatin1String(NM_NOVELLVPN_KEY_NOSPLITTUNNEL), d->advUi.cbDisableSplit->isChecked() ? QLatin1String("yes") : QLatin1String("no"));

    d->setting->setData(data);
    d->setting->setVpnSecrets(secretData);
}
Beispiel #7
0
QDomDocument SOAPClient::SendSOAPRequest(const QString &sMethod,
                                         QStringMap    &list,
                                         int           &nErrCode,
                                         QString       &sErrDesc)
{
    QUrl url(m_url);

    url.setPath(m_sControlPath);

    nErrCode = UPnPResult_Success;
    sErrDesc = "";

    QDomDocument xmlResult;
    if (m_sNamespace.isEmpty())
    {
        nErrCode = UPnPResult_MythTV_NoNamespaceGiven;
        sErrDesc = "No namespace given";
        return xmlResult;
    }

    // --------------------------------------------------------------
    // Add appropriate headers
    // --------------------------------------------------------------
    QHash<QByteArray, QByteArray> headers;

    headers.insert("Content-Type", "text/xml; charset=\"utf-8\"");
    QString soapHeader = QString("\"%1#%2\"").arg(m_sNamespace).arg(sMethod);
	headers.insert("SOAPACTION", soapHeader.toUtf8());
    headers.insert("User-Agent", "Mozilla/9.876 (X11; U; Linux 2.2.12-20 i686, en) "
                                 "Gecko/25250101 Netscape/5.432b1");
    // --------------------------------------------------------------
    // Build request payload
    // --------------------------------------------------------------

    QByteArray  aBuffer;
    QTextStream os( &aBuffer );

    os.setCodec("UTF-8");

    os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"; 
    os << "<s:Envelope "
        " s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\""
        " xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
    os << " <s:Body>\r\n";
    os << "  <u:" << sMethod << " xmlns:u=\"" << m_sNamespace << "\">\r\n";

    // --------------------------------------------------------------
    // Add parameters from list
    // --------------------------------------------------------------

    for (QStringMap::iterator it = list.begin(); it != list.end(); ++it)
    {                                                               
        os << "   <" << it.key() << ">";
        os << HTTPRequest::Encode( *it );
        os << "</"   << it.key() << ">\r\n";
    }

    os << "  </u:" << sMethod << ">\r\n";
    os << " </s:Body>\r\n";
    os << "</s:Envelope>\r\n";

    os.flush();

    // --------------------------------------------------------------
    // Perform Request
    // --------------------------------------------------------------

    LOG(VB_UPNP, LOG_DEBUG,
        QString("SOAPClient(%1) sending:\n %2").arg(url.toString()).arg(aBuffer.constData()));

    QString sXml;

    if (!GetMythDownloadManager()->postAuth(url.toString(), &aBuffer, NULL, NULL, &headers))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("SOAPClient::SendSOAPRequest: request failed: %1")
                                         .arg(url.toString()));
    }
    else
        sXml = QString(aBuffer);

    // --------------------------------------------------------------
    // Parse response
    // --------------------------------------------------------------

    LOG(VB_UPNP, LOG_DEBUG, "SOAPClient response:\n" +
                            QString("%1\n").arg(sXml));

    // TODO handle timeout without response correctly.

    list.clear();

    QDomDocument doc;

    if (!doc.setContent(sXml, true, &sErrDesc, &nErrCode))
    {
        LOG(VB_UPNP, LOG_ERR,
            QString("SendSOAPRequest( %1 ) - Invalid response from %2")
                .arg(sMethod).arg(url.toString()) + 
            QString("%1: %2").arg(nErrCode).arg(sErrDesc));

        return xmlResult;
    }

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QString      sResponseName = sMethod + "Response";
    QDomNodeList oNodeList     =
        doc.elementsByTagNameNS(m_sNamespace, sResponseName);

    if (oNodeList.count() == 0)
    {
        // --------------------------------------------------------------
        // Must be a fault... parse it to return reason
        // --------------------------------------------------------------

        nErrCode = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorCode", 500);
        sErrDesc = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorDescription", "");
        if (sErrDesc.isEmpty())
            sErrDesc = QString("Unknown #%1").arg(nErrCode);

        QDomNode oNode  = FindNode( "Envelope/Body/Fault", doc );

        oNode = xmlResult.importNode( oNode, true );
        xmlResult.appendChild( oNode );

        return xmlResult;
    }

    QDomNode oMethod = oNodeList.item(0);
    if (oMethod.isNull())
        return xmlResult;

    QDomNode oNode = oMethod.firstChild(); 
    for (; !oNode.isNull(); oNode = oNode.nextSibling())
    {
        QDomElement e = oNode.toElement();
        if (e.isNull())
            continue;

        QString sName  = e.tagName();
        QString sValue = "";
    
        QDomText  oText = oNode.firstChild().toText();
    
        if (!oText.isNull())
            sValue = oText.nodeValue();

        list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
                    QUrl::fromPercentEncoding(sValue.toUtf8()));
    }

    // Create copy of oMethod that can be used with xmlResult.

    oMethod = xmlResult.importNode( oMethod.firstChild(), true  );

    // importNode does not attach the new nodes to the document,
    // do it here.

    xmlResult.appendChild( oMethod );

    return xmlResult;
}
void VpncSettingWidget::writeConfig()
{
    Q_D(VpncSettingWidget);
    kDebug();

    d->setting->setServiceType(QLatin1String(NM_DBUS_SERVICE_VPNC));

    QStringMap data;
    QStringMap secretData;

    // General settings
    //   gateway
    if (!d->ui.leGateway->text().isEmpty()) {
        data.insert(NM_VPNC_KEY_GATEWAY, d->ui.leGateway->text());
    }

    //   group name
    if (!d->ui.leGroupName->text().isEmpty()) {
        data.insert(NM_VPNC_KEY_ID, d->ui.leGroupName->text());
    }

    //   user password
    if (!d->ui.leUserPassword->text().isEmpty() && d->ui.cboUserPassOptions->currentIndex() == VpncSettingWidgetPrivate::EnumPasswordStorage::Save) {
        secretData.insert(NM_VPNC_KEY_XAUTH_PASSWORD, d->ui.leUserPassword->text());
    }
    //   group password
    if (!d->ui.leGroupPassword->text().isEmpty() && d->ui.cboGroupPassOptions->currentIndex() == VpncSettingWidgetPrivate::EnumPasswordStorage::Save) {
        secretData.insert(NM_VPNC_KEY_SECRET, d->ui.leGroupPassword->text());
    }
    handleOnePasswordType(d->ui.cboUserPassOptions, NM_VPNC_KEY_XAUTH_PASSWORD"-flags", data);
    handleOnePasswordType(d->ui.cboGroupPassOptions, NM_VPNC_KEY_SECRET"-flags", data);

    // hybrid auth
    if (d->ui.cbUseHybridAuth->isChecked()) {
        data.insert(NM_VPNC_KEY_AUTHMODE, QLatin1String("hybrid"));
        data.insert(NM_VPNC_KEY_CA_FILE, d->ui.leCaCertPath->url().path());
    }

    // Optional settings
    //   username
    if (!d->ui.leUserName->text().isEmpty()) {
        data.insert(NM_VPNC_KEY_XAUTH_USER, d->ui.leUserName->text());
    }

    //   domain
    if (!d->ui.leDomain->text().isEmpty()) {
        data.insert(NM_VPNC_KEY_DOMAIN, d->ui.leDomain->text());
    }

    //   encryption
    switch (d->ui.cboEncryptionMethod->currentIndex()) {
    case VpncSettingWidgetPrivate::EnumEncryptionMethod::Weak:
        data.insert(NM_VPNC_KEY_SINGLE_DES, QLatin1String("yes"));
        break;
    case VpncSettingWidgetPrivate::EnumEncryptionMethod::None:
        data.insert(NM_VPNC_KEY_NO_ENCRYPTION, QLatin1String("yes"));
        break;
    default:
        break;
    }

    // nat traversal
    switch (d->ui.cboNatTraversal->currentIndex()) {
    case VpncSettingWidgetPrivate::EnumNatt::Force:
        data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NATT_ALWAYS));
        break;
    case VpncSettingWidgetPrivate::EnumNatt::CiscoUdp:
        data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_CISCO));
        break;
    case VpncSettingWidgetPrivate::EnumNatt::Disabled:
        data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NONE));
        break;
    case VpncSettingWidgetPrivate::EnumNatt::NattIfAvail:
    default:
        data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NATT));
        break;
    }

    // dead peer detection
    if (d->ui.chkDeadPeerDetection->isChecked()) {
        if (d->dpdTimeout > 0) {
            data.insert(NM_VPNC_KEY_DPD_IDLE_TIMEOUT, QString::number(d->dpdTimeout));
        }
    } else {
        data.insert(NM_VPNC_KEY_DPD_IDLE_TIMEOUT, QString::number(0));
    }

    // dh group
    switch (d->ui.cboDHGroup->currentIndex()) {
    case VpncSettingWidgetPrivate::EnumDh::Dh1:	// DH Group 1
        data.insert(NM_VPNC_KEY_DHGROUP, NM_VPNC_DHGROUP_DH1);
        break;
    case VpncSettingWidgetPrivate::EnumDh::Dh2:	// DH Group 2
        data.insert(NM_VPNC_KEY_DHGROUP, NM_VPNC_DHGROUP_DH2);
        break;
    case VpncSettingWidgetPrivate::EnumDh::Dh5:	// DH Group 5
        data.insert(NM_VPNC_KEY_DHGROUP, NM_VPNC_DHGROUP_DH5);
        break;
    }

    // Perfect Forward Secrecy
    switch (d->ui.cboPerfectForwardSecrecy->currentIndex()) {
    case VpncSettingWidgetPrivate::EnumPerfectForwardSecrecy::NoPfs:
        data.insert(NM_VPNC_KEY_PERFECT_FORWARD, QLatin1String("nopfs"));
        break;
    case VpncSettingWidgetPrivate::EnumPerfectForwardSecrecy::Server:
        data.insert(NM_VPNC_KEY_PERFECT_FORWARD, QLatin1String("server"));
        break;
    case VpncSettingWidgetPrivate::EnumPerfectForwardSecrecy::Dh1:
        data.insert(NM_VPNC_KEY_PERFECT_FORWARD, QLatin1String("dh1"));
        break;
    case VpncSettingWidgetPrivate::EnumPerfectForwardSecrecy::Dh2:
        data.insert(NM_VPNC_KEY_PERFECT_FORWARD, QLatin1String("dh2"));
        break;
    case VpncSettingWidgetPrivate::EnumPerfectForwardSecrecy::Dh5:
        data.insert(NM_VPNC_KEY_PERFECT_FORWARD, QLatin1String("dh5"));
        break;
    }

    // Vendor
    switch (d->ui.cboVendor->currentIndex()) {
    case VpncSettingWidgetPrivate::EnumVendor::Cisco:
        data.insert(NM_VPNC_KEY_VENDOR, QLatin1String("cisco"));
        break;
    case VpncSettingWidgetPrivate::EnumVendor::Netscreen:
        data.insert(NM_VPNC_KEY_VENDOR, QLatin1String("netscreen"));
        break;
    }

    // Application Version
    if (!d->ui.leApplicationVersion->text().isEmpty()) {
        data.insert(NM_VPNC_KEY_APP_VERSION, d->ui.leApplicationVersion->text());
    }

    // Local Port
    data.insert(NM_VPNC_KEY_LOCAL_PORT, QString::number(d->ui.spbLocalPort->value()));

    // Cisco UDP Encapsulation Port
    data.insert(NM_VPNC_KEY_CISCO_UDP_ENCAPS_PORT, QString::number(d->ui.spbCiscoUdpEncPort->value()));

    d->setting->setData(data);
    d->setting->setVpnSecrets(secretData);
}
Beispiel #9
0
void SSDP::ProcessData( MSocketDevice *pSocket )
{
    long nBytes = 0;
    long nRead  = 0;

    while ((nBytes = pSocket->bytesAvailable()) > 0)
    {
        QByteArray buffer;
        buffer.resize(nBytes);

        nRead = pSocket->readBlock( buffer.data(), nBytes );

        QHostAddress  peerAddress = pSocket->peerAddress();
        quint16       peerPort    = pSocket->peerPort   ();

        // ------------------------------------------------------------------
        QString     str          = QString(buffer.constData());
        QStringList lines        = str.split("\r\n", QString::SkipEmptyParts);
        QString     sRequestLine = lines.size() ? lines[0] : "";

        lines.pop_front();

        // ------------------------------------------------------------------
        // Parse request Type
        // ------------------------------------------------------------------

        VERBOSE(VB_UPNP+VB_EXTRA,
                QString( "SSDP::ProcessData - requestLine: %1" )
                .arg( sRequestLine ));

        SSDPRequestType eType = ProcessRequestLine( sRequestLine );

        // ------------------------------------------------------------------
        // Read Headers into map
        // ------------------------------------------------------------------

        QStringMap  headers;

        for ( QStringList::Iterator it = lines.begin();
                                    it != lines.end(); ++it ) 
        {
            QString sLine  = *it;
            QString sName  = sLine.section( ':', 0, 0 ).trimmed();
            QString sValue = sLine.section( ':', 1 );

            sValue.truncate( sValue.length() );  //-2

            if ((sName.length() != 0) && (sValue.length() !=0))
                headers.insert( sName.toLower(), sValue.trimmed() );
        }

//        pSocket->SetDestAddress( peerAddress, peerPort );

        // --------------------------------------------------------------
        // See if this is a valid request
        // --------------------------------------------------------------

        switch( eType )
        {
            case SSDP_MSearch:
            {
                // ----------------------------------------------------------
                // If we haven't enabled notifications yet, then we don't 
                // want to answer search requests.
                // ----------------------------------------------------------

                if (m_pNotifyTask != NULL)
                    ProcessSearchRequest( headers, peerAddress, peerPort ); 

                break;
            }

            case SSDP_MSearchResp:
                ProcessSearchResponse( headers); 
                break;

            case SSDP_Notify:
                ProcessNotify( headers ); 
                break;

            case SSDP_Unknown:
            default:
                VERBOSE(VB_UPNP, "SSPD::ProcessData - Unknown request Type.");
                break;
        }
    }

}
Beispiel #10
0
/** Actually sends the sMethod action to the command URL specified
 *  in the constructor (url+[/]+sControlPath).
 *
 * \param sMethod method to be invoked. e.g. "SetChannel",
 *                "GetConnectionInfoResult"
 *
 * \param list Parsed as a series of key value pairs for the input params
 *             and then cleared and used for the output params.
 *
 * \param nErrCode set to zero on success, non-zero in case of error.
 *
 * \param sErrCode returns error description from device, when applicable.
 *
 * \param bInQtThread May be set to true if this is run from within
 *                    a QThread with a running an event loop.
 *
 * \return Returns a QDomDocument containing output parameters on success.
 */
QDomDocument SOAPClient::SendSOAPRequest(const QString &sMethod,
                                         QStringMap    &list,
                                         int           &nErrCode,
                                         QString       &sErrDesc,
                                         bool           bInQtThread)
{
    QUrl url(m_url);

    url.setPath(m_sControlPath);

    nErrCode = UPnPResult_Success;
    sErrDesc = "";

    QDomDocument xmlResult;
    if (m_sNamespace.isEmpty())
    {
        nErrCode = UPnPResult_MythTV_NoNamespaceGiven;
        sErrDesc = "No namespace given";
        return xmlResult;
    }

    // --------------------------------------------------------------
    // Add appropriate headers
    // --------------------------------------------------------------

    QHttpRequestHeader header("POST", sMethod, 1, 0);

    header.setValue("CONTENT-TYPE", "text/xml; charset=\"utf-8\"" );
    header.setValue("SOAPACTION",
                    QString("\"%1#%2\"").arg(m_sNamespace).arg(sMethod));

    // --------------------------------------------------------------
    // Build request payload
    // --------------------------------------------------------------

    QByteArray  aBuffer;
    QTextStream os( &aBuffer );

    os.setCodec("UTF-8");

    os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"; 
    os << "<s:Envelope "
        " s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\""
        " xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
    os << " <s:Body>\r\n";
    os << "  <u:" << sMethod << " xmlns:u=\"" << m_sNamespace << "\">\r\n";

    // --------------------------------------------------------------
    // Add parameters from list
    // --------------------------------------------------------------

    for (QStringMap::iterator it = list.begin(); it != list.end(); ++it)
    {                                                               
        os << "   <" << it.key() << ">";
        os << HTTPRequest::Encode( *it );
        os << "</"   << it.key() << ">\r\n";
    }

    os << "  </u:" << sMethod << ">\r\n";
    os << " </s:Body>\r\n";
    os << "</s:Envelope>\r\n";

    os.flush();

    // --------------------------------------------------------------
    // Perform Request
    // --------------------------------------------------------------

    QBuffer buff(&aBuffer);

    LOG(VB_UPNP, LOG_DEBUG,
        QString("SOAPClient(%1) sending:\n").arg(url.toString()) +
        header.toString() + QString("\n%1\n").arg(aBuffer.constData()));

    QString sXml =
        HttpComms::postHttp(url,
                            &header,
                            &buff, // QIODevice*
                            10000, // ms -- Technically should be 30ms per spec
                            3,     // retries
                            0,     // redirects
                            false, // allow gzip
                            NULL,  // login
                            bInQtThread,
                            QString() // userAgent, UPnP/1.0 very strict on
                                      // format if set
        );

    // --------------------------------------------------------------
    // Parse response
    // --------------------------------------------------------------

    LOG(VB_UPNP, LOG_DEBUG, "SOAPClient response:\n" +
                            QString("%1\n").arg(sXml));

    // TODO handle timeout without response correctly.

    list.clear();

    QDomDocument doc;

    if (!doc.setContent(sXml, true, &sErrDesc, &nErrCode))
    {
        LOG(VB_UPNP, LOG_ERR,
            QString("SendSOAPRequest( %1 ) - Invalid response from %2")
                .arg(sMethod).arg(url.toString()) + 
            QString("%1: %2").arg(nErrCode).arg(sErrDesc));

        return xmlResult;
    }

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QString      sResponseName = sMethod + "Response";
    QDomNodeList oNodeList     =
        doc.elementsByTagNameNS(m_sNamespace, sResponseName);

    if (oNodeList.count() == 0)
    {
        // --------------------------------------------------------------
        // Must be a fault... parse it to return reason
        // --------------------------------------------------------------

        nErrCode = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorCode", 500);
        sErrDesc = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorDescription", "");
        if (sErrDesc.isEmpty())
            sErrDesc = QString("Unknown #%1").arg(nErrCode);

        QDomNode oNode  = FindNode( "Envelope/Body/Fault", doc );

        oNode = xmlResult.importNode( oNode, true );
        xmlResult.appendChild( oNode );

        return xmlResult;
    }

    QDomNode oMethod = oNodeList.item(0);
    if (oMethod.isNull())
        return xmlResult;

    QDomNode oNode = oMethod.firstChild(); 
    for (; !oNode.isNull(); oNode = oNode.nextSibling())
    {
        QDomElement e = oNode.toElement();
        if (e.isNull())
            continue;

        QString sName  = e.tagName();
        QString sValue = "";
    
        QDomText  oText = oNode.firstChild().toText();
    
        if (!oText.isNull())
            sValue = oText.nodeValue();

        list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
                    QUrl::fromPercentEncoding(sValue.toUtf8()));
    }

    // Create copy of oMethod that can be used with xmlResult.

    oMethod = xmlResult.importNode( oMethod.firstChild(), true  );

    // importNode does not attach the new nodes to the document,
    // do it here.

    xmlResult.appendChild( oMethod );

    return xmlResult;
}
Beispiel #11
0
bool SOAPClient::SendSOAPRequest( const QString    &sMethod, 
                                        QStringMap &list, 
                                        int        &nErrCode, 
                                        QString    &sErrDesc,
                                        bool        bInQtThread )
{
    QUrl url( m_url );

    url.setPath( m_sControlPath );

    // --------------------------------------------------------------
    // Add appropriate headers
    // --------------------------------------------------------------

    QHttpRequestHeader header;

    header.setValue("CONTENT-TYPE", "text/xml; charset=\"utf-8\"" );
    header.setValue("SOAPACTION"  , QString( "\"%1#GetConnectionInfo\"" )
                                       .arg( m_sNamespace ));

    // --------------------------------------------------------------
    // Build request payload
    // --------------------------------------------------------------

    QByteArray  aBuffer;
    QTextStream os( &aBuffer );

    os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"; 
    os << "<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
    os << " <s:Body>\r\n";
    os << "  <u:" << sMethod << " xmlns:u=\"" << m_sNamespace << "\">\r\n";

    // --------------------------------------------------------------
    // Add parameters from list
    // --------------------------------------------------------------

    for ( QStringMap::iterator it  = list.begin(); 
                               it != list.end(); 
                             ++it ) 
    {                                                               
        os << "   <" << it.key() << ">";
        os << HTTPRequest::Encode( *it );
        os << "</"   << it.key() << ">\r\n";
    }

    os << "  </u:" << sMethod << ">\r\n";
    os << " </s:Body>\r\n";
    os << "</s:Envelope>\r\n";

    os.flush();

    // --------------------------------------------------------------
    // Perform Request
    // --------------------------------------------------------------

    QBuffer     buff( &aBuffer );

    QString sXml = HttpComms::postHttp( url, 
                                        &header,
                                        (QIODevice *)&buff,
                                        10000, // ms
                                        3,     // retries
                                        0,     // redirects
                                        false, // allow gzip
                                        NULL,  // login
                                        bInQtThread );

    // --------------------------------------------------------------
    // Parse response
    // --------------------------------------------------------------

    list.clear();

    QDomDocument doc;

    if ( !doc.setContent( sXml, true, &sErrDesc, &nErrCode ))
    {
        VERBOSE( VB_UPNP, QString( "MythXMLClient::SendSOAPRequest( %1 ) - Invalid response from %2" )
                             .arg( sMethod   )
                             .arg( url.toString() ));
        return false;
    }

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QString      sResponseName = sMethod + "Response";
    QDomNodeList oNodeList     = doc.elementsByTagNameNS( m_sNamespace, sResponseName );

    if (oNodeList.count() > 0)
    {
        QDomNode oMethod = oNodeList.item(0);

        if (!oMethod.isNull())
        {

            for ( QDomNode oNode = oMethod.firstChild(); !oNode.isNull(); 
                           oNode = oNode.nextSibling() )
            {
                QDomElement e = oNode.toElement();

                if (!e.isNull())
                {
                    QString sName  = e.tagName();
                    QString sValue = "";
    
                    QDomText  oText = oNode.firstChild().toText();
    
                    if (!oText.isNull())
                        sValue = oText.nodeValue();

                    list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
                                QUrl::fromPercentEncoding(sValue.toUtf8()));
                }
            }
        }

        return true;
    }

    // --------------------------------------------------------------
    // Must be a fault... parse it to return reason
    // --------------------------------------------------------------

    nErrCode = GetNodeValue( doc, "Envelope/Body/Fault/detail/UPnPResult/errorCode"       , 500 );
    sErrDesc = GetNodeValue( doc, "Envelope/Body/Fault/detail/UPnPResult/errorDescription", QString( "Unknown" ));

    return false;
}
Beispiel #12
0
UPnPResultCode MythXMLClient::GetConnectionInfo( const QString &sPin, DatabaseParams *pParams, QString &sMsg )
{
    if (pParams == NULL)
        return UPnPResult_InvalidArgs;

    int           nErrCode = 0;
    QString       sErrDesc;
    QStringMap    list;

    sMsg.clear();

    list.insert( "Pin", sPin );

    QDomDocument xmlResults = SendSOAPRequest(
        "GetConnectionInfo", list, nErrCode, sErrDesc, m_bInQtThread);

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QDomNode oNode = xmlResults.namedItem( "GetConnectionInfoResult" );

    if (UPnPResult_Success == nErrCode && !oNode.isNull())
    {
        QDomNode dbNode = oNode.namedItem( "Database" );

        pParams->dbHostName   = GetNodeValue( dbNode, "Host"     , QString());
        pParams->dbPort       = GetNodeValue( dbNode, "Port"     , 0        );
        pParams->dbUserName   = GetNodeValue( dbNode, "UserName" , QString());
        pParams->dbPassword   = GetNodeValue( dbNode, "Password" , QString());
        pParams->dbName       = GetNodeValue( dbNode, "Name"     , QString());
        pParams->dbType       = GetNodeValue( dbNode, "Type"     , QString());

        QDomNode wolNode = oNode.namedItem( "WOL" );

        pParams->wolEnabled   = GetNodeValue( wolNode, "Enabled"  , false    );
        pParams->wolReconnect = GetNodeValue( wolNode, "Reconnect", 0        );
        pParams->wolRetry     = GetNodeValue( wolNode, "Retry"    , 0        );
        pParams->wolCommand   = GetNodeValue( wolNode, "Command"  , QString());

        return UPnPResult_Success;
    }
    else
    {
        sMsg = sErrDesc;

        LOG(VB_GENERAL, LOG_ERR,
            QString("MythXMLClient::GetConnectionInfo Failed - (%1) %2")
                .arg(nErrCode) .arg(sErrDesc));
    }

    if (( nErrCode == UPnPResult_HumanInterventionRequired ) || 
        ( nErrCode == UPnPResult_ActionNotAuthorized       ) ||
        ( nErrCode == 501                                  ))
    {
        // Service calls no longer return UPnPResult codes, 
        // convert standard 501 to UPnPResult code for now.
        return UPnPResult_ActionNotAuthorized;
    }

    return UPnPResult_ActionFailed;
}
Beispiel #13
0
UPnPResultCode MythXMLClient::GetConnectionInfo( const QString &sPin, DatabaseParams *pParams, QString &sMsg )
{
    if (pParams == NULL)
        return UPnPResult_InvalidArgs;

    int           nErrCode = 0;
    QString       sErrDesc;
    QStringMap    list;

    sMsg.clear();

    list.insert( "Pin", sPin );

    if (SendSOAPRequest( "GetConnectionInfo", list, nErrCode, sErrDesc, m_bInQtThread ))
    {
        QString sXml = "<Info>" + list[ "Info" ] + "</Info>";

        sMsg = sErrDesc;

        QDomDocument doc;

        if ( !doc.setContent( sXml, false, &sErrDesc, &nErrCode ))
        {
            sMsg = QObject::tr("Error Requesting Connection Info");

            VERBOSE( VB_UPNP, QString( "Error Requesting Connection Info : (%1) - %2" )
                                 .arg( nErrCode )
                                 .arg( sErrDesc ) );

            return UPnPResult_ActionFailed;
        }

        // --------------------------------------------------------------
        // Is this a valid response?
        // --------------------------------------------------------------

        QDomNode infoNode = doc.namedItem( "Info" );

        if (!infoNode.isNull())
        {
            QDomNode dbNode = infoNode.namedItem( "Database" );

            pParams->dbHostName     = GetNodeValue( dbNode, "Host"     , QString( ));
            pParams->dbPort         = GetNodeValue( dbNode, "Port"     , 0         );
            pParams->dbUserName     = GetNodeValue( dbNode, "UserName" , QString( ));
            pParams->dbPassword     = GetNodeValue( dbNode, "Password" , QString( ));
            pParams->dbName         = GetNodeValue( dbNode, "Name"     , QString( ));
            pParams->dbType         = GetNodeValue( dbNode, "Type"     , QString( ));

            QDomNode wolNode = infoNode.namedItem( "WOL" );

            pParams->wolEnabled     = GetNodeValue( wolNode, "Enabled"  , false     );
            pParams->wolReconnect   = GetNodeValue( wolNode, "Reconnect", 0         );
            pParams->wolRetry       = GetNodeValue( wolNode, "Retry"    , 0         );
            pParams->wolCommand     = GetNodeValue( wolNode, "Command"  , QString( ));

            return UPnPResult_Success;
        }
        else
        {
            if (sMsg.isEmpty())
                sMsg = QObject::tr("Unexpected Response");

            VERBOSE( VB_IMPORTANT, QString( "MythXMLClient::GetConnectionInfo Failed : Unexpected Response - %1" )
                                      .arg( sXml   ));
        }
    }
    else
    {
        sMsg = sErrDesc;

        if (sMsg.isEmpty())
            sMsg = QObject::tr("Access Denied");

        VERBOSE( VB_IMPORTANT, QString( "MythXMLClient::GetConnectionInfo Failed - (%1) %2" )
                             .arg( nErrCode )
                             .arg( sErrDesc ));
    }

    if (UPnPResult_HumanInterventionRequired == nErrCode
           || UPnPResult_ActionNotAuthorized == nErrCode)
        return (UPnPResultCode)nErrCode;

    return UPnPResult_ActionFailed;
}
Beispiel #14
0
UPnPResultCode MythXMLClient::GetConnectionInfo( const QString &sPin, DatabaseParams *pParams, QString &sMsg )
{
    if (pParams == NULL)
        return UPnPResult_InvalidArgs;

    int           nErrCode = 0;
    QString       sErrDesc;
    QStringMap    list;

    sMsg.clear();

    list.insert( "Pin", sPin );

    QDomDocument xmlResults = SendSOAPRequest(
        "GetConnectionInfo", list, nErrCode, sErrDesc, m_bInQtThread);

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QDomNode oNode = xmlResults.namedItem( "GetConnectionInfoResult" );

    if (UPnPResult_Success == nErrCode && !oNode.isNull())
    {
        QDomNode dbNode = oNode.namedItem( "Database" );

        pParams->dbHostName   = GetNodeValue( dbNode, "Host"     , QString());
        pParams->dbPort       = GetNodeValue( dbNode, "Port"     , 0        );
        pParams->dbUserName   = GetNodeValue( dbNode, "UserName" , QString());
        pParams->dbPassword   = GetNodeValue( dbNode, "Password" , QString());
        pParams->dbName       = GetNodeValue( dbNode, "Name"     , QString());
        pParams->dbType       = GetNodeValue( dbNode, "Type"     , QString());

        QDomNode wolNode = oNode.namedItem( "WOL" );

        pParams->wolEnabled   = GetNodeValue( wolNode, "Enabled"  , false    );
        pParams->wolReconnect = GetNodeValue( wolNode, "Reconnect", 0        );
        pParams->wolRetry     = GetNodeValue( wolNode, "Retry"    , 0        );
        pParams->wolCommand   = GetNodeValue( wolNode, "Command"  , QString());

        QDomNode verNode = oNode.namedItem( "Version" );

        pParams->verVersion   = GetNodeValue( verNode, "Version"  , ""       );
        pParams->verBranch    = GetNodeValue( verNode, "Branch"   , ""       );
        pParams->verProtocol  = GetNodeValue( verNode, "Protocol" , ""       );
        pParams->verBinary    = GetNodeValue( verNode, "Binary"   , ""       );
        pParams->verSchema    = GetNodeValue( verNode, "Schema"   , ""       );

        if ((pParams->verProtocol != MYTH_PROTO_VERSION) ||
            (pParams->verSchema   != MYTH_DATABASE_VERSION))
            // incompatible version, we cannot use this backend
        {
            LOG(VB_GENERAL, LOG_ERR,
                QString("MythXMLClient::GetConnectionInfo Failed - "
                        "Version Mismatch (%1,%2) != (%3,%4)")
                .arg(pParams->verProtocol)
                .arg(pParams->verSchema)
                .arg(MYTH_PROTO_VERSION)
                .arg(MYTH_DATABASE_VERSION));
            sMsg = QObject::tr("Version Mismatch", "UPNP Errors");
            return UPnPResult_ActionFailed;
        }

        return UPnPResult_Success;
    }
    else
    {
        sMsg = sErrDesc;

        LOG(VB_GENERAL, LOG_ERR,
            QString("MythXMLClient::GetConnectionInfo Failed - (%1) %2")
                .arg(nErrCode) .arg(sErrDesc));
    }

    if (( nErrCode == UPnPResult_HumanInterventionRequired ) || 
        ( nErrCode == UPnPResult_ActionNotAuthorized       ) ||
        ( nErrCode == 501                                  ))
    {
        // Service calls no longer return UPnPResult codes, 
        // convert standard 501 to UPnPResult code for now.
        sMsg = QObject::tr("Not Authorized", "UPNP Errors");
        return UPnPResult_ActionNotAuthorized;
    }

    sMsg = QObject::tr("Unknown Error", "UPNP Errors");
    return UPnPResult_ActionFailed;
}