void NovellVpnSettingWidget::readSecrets() { QStringMap secrets = d->setting->vpnSecrets(); kDebug() << "Value of" << NM_NOVELLVPN_KEY_CERT_PWD << secrets.value(QLatin1String(NM_NOVELLVPN_KEY_CERT_PWD)); d->ui.x509CertPass->setText(secrets.value(QLatin1String(NM_NOVELLVPN_KEY_CERT_PWD))); d->ui.leUserPass->setText(secrets.value(QLatin1String(NM_NOVELLVPN_KEY_USER_PWD))); d->ui.leGroupPass->setText(secrets.value(QLatin1String(NM_NOVELLVPN_KEY_GRP_PWD))); }
QString SSDP::GetHeaderValue( const QStringMap &headers, const QString &sKey, const QString &sDefault ) { QStringMap::const_iterator it = headers.find( sKey.toLower() ); if ( it == headers.end()) return( sDefault ); return *it; }
/** * This controller needs the parameter 'machine' with the name of the machine * * \param[in] params The parameter map */ void InfoController::setParams(const QStringMap& params) { if( !params.contains("machine") || !params.contains("machine")) { std::cerr << "InfoController: Required parameter not found" << std::endl; return; } _machine = params["machine"]; _model.setDatabaseFile( params["db"] ); }
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; }
QVariantMap convertToVariant(const QStringMap &val) { QVariantMap ret; for(const QString &k : val.keys()) { ret[k] = val[k]; } return ret; }
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; }
void VpncSettingWidget::readSecrets() { Q_D(VpncSettingWidget); QStringMap secrets = d->setting->vpnSecrets(); Knm::Setting::secretsTypes userType; Knm::Setting::secretsTypes groupType; userType = (Knm::Setting::secretsTypes)d->setting->data().value(NM_VPNC_KEY_XAUTH_PASSWORD"-flags").toInt(); if (userType & Knm::Setting::AgentOwned || userType & Knm::Setting::None || !userType) { d->ui.leUserPassword->setText(secrets.value(QLatin1String(NM_VPNC_KEY_XAUTH_PASSWORD))); } fillOnePasswordCombo(d->ui.cboUserPassOptions, userType); groupType = (Knm::Setting::secretsTypes)d->setting->data().value(NM_VPNC_KEY_SECRET"-flags").toInt(); if (groupType & Knm::Setting::AgentOwned || groupType & Knm::Setting::None || !groupType) { d->ui.leGroupPassword->setText(secrets.value(QLatin1String(NM_VPNC_KEY_SECRET))); } fillOnePasswordCombo(d->ui.cboGroupPassOptions, groupType); }
void MythFEXML::SendAction(HTTPRequest *pRequest) { QStringMap* map = &pRequest->m_mapParams; pRequest->m_eResponseType = ResponseTypeHTML; QString sText = map->value("action"); uint pcount = map->size(); VERBOSE(VB_UPNP, QString("UPNP Action: %1 (total %2 params)") .arg(sText).arg(pcount)); if (!IsValidAction(sText)) return; if (pcount > 1) { bool valid = false; QStringList args; if (ACTION_SCREENSHOT == sText && 3 == pcount) { args << map->value("width"); args << map->value("height"); valid = true; } else if (ACTION_HANDLEMEDIA == sText && 2 == pcount) { args << map->value("file"); valid = true; } if (valid) { MythEvent* me = new MythEvent(sText, args); qApp->postEvent(GetMythMainWindow(), me); return; } VERBOSE(VB_UPNP, QString("Failed to validate extra paramaters - ignoring")); } QKeyEvent* ke = new QKeyEvent(QEvent::KeyPress, 0, Qt::NoModifier, sText); qApp->postEvent(GetMythMainWindow(), (QEvent*)ke); }
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; } } }
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()); }
bool ServerSideScripting::EvaluatePage( QTextStream *pOutStream, const QString &sFileName, HTTPRequest *pRequest) { try { ScriptInfo *pInfo = NULL; // ------------------------------------------------------------------ // See if page has already been loaded // ------------------------------------------------------------------ pInfo = GetLoadedScript( sFileName ); // ------------------------------------------------------------------ // Load Script File and Create Function // ------------------------------------------------------------------ QFileInfo fileInfo ( sFileName ); QDateTime dtLastModified = fileInfo.lastModified(); Lock(); if ((pInfo == NULL) || (pInfo->m_dtTimeStamp != dtLastModified )) { QString sCode = CreateMethodFromFile( sFileName ); QScriptValue func = m_engine.evaluate( sCode, sFileName ); if ( m_engine.hasUncaughtException() ) { LOG(VB_GENERAL, LOG_ERR, QString("Error Loading QSP File: %1 - (line %2) %3") .arg(sFileName) .arg(m_engine.uncaughtExceptionLineNumber()) .arg(m_engine.uncaughtException().toString())); Unlock(); return false; } if (pInfo != NULL) { pInfo->m_oFunc = func; pInfo->m_dtTimeStamp = dtLastModified; } else { pInfo = new ScriptInfo( func, dtLastModified ); m_mapScripts[ sFileName ] = pInfo; } } // ------------------------------------------------------------------ // Build array of arguments passed to script // ------------------------------------------------------------------ QStringMap mapParams = pRequest->m_mapParams; // Valid characters for object property names must contain only // word characters and numbers, _ and $ // They must not start with a number - to simplify the regexp, we // restrict the first character to the English alphabet QRegExp validChars = QRegExp("^([a-zA-Z]|_|\\$)(\\w|\\$)+$"); QVariantMap params; QMap<QString, QString>::const_iterator it = mapParams.begin(); QString prevArrayName = ""; QVariantMap array; for (; it != mapParams.end(); ++it) { QString key = it.key(); QVariant value = QVariant(it.value()); // PHP Style parameter array if (key.contains("[")) { QString arrayName = key.section('[',0,0); QString arrayKey = key.section('[',1,1); arrayKey.chop(1); // Remove trailing ] if (prevArrayName != arrayName) // New or different array { if (!array.isEmpty()) { params.insert(prevArrayName, QVariant(array)); array.clear(); } prevArrayName = arrayName; } if (!validChars.exactMatch(arrayKey)) // Discard anything that isn't valid for now continue; array.insert(arrayKey, value); if ((it + 1) != mapParams.end()) continue; } if (!array.isEmpty()) { params.insert(prevArrayName, QVariant(array)); array.clear(); } // End Array handling if (!validChars.exactMatch(key)) // Discard anything that isn't valid for now continue; params.insert(key, value); } // ------------------------------------------------------------------ // Build array of request headers // ------------------------------------------------------------------ QStringMap mapHeaders = pRequest->m_mapHeaders; QVariantMap requestHeaders; for (it = mapHeaders.begin(); it != mapHeaders.end(); ++it) { QString key = it.key(); key = key.replace('-', '_'); // May be other valid chars in a request header that we need to replace QVariant value = QVariant(it.value()); if (!validChars.exactMatch(key)) // Discard anything that isn't valid for now continue; requestHeaders.insert(key, value); } // ------------------------------------------------------------------ // Build array of information from the server e.g. client IP // See RFC 3875 - The Common Gateway Interface // ------------------------------------------------------------------ QVariantMap serverVars; serverVars.insert("REMOTE_ADDR", QVariant(pRequest->GetPeerAddress())); serverVars.insert("SERVER_ADDR", QVariant(pRequest->GetHostAddress())); serverVars.insert("SERVER_PROTOCOL", QVariant(pRequest->GetRequestProtocol())); serverVars.insert("SERVER_SOFTWARE", QVariant(HttpServer::GetServerVersion())); QHostAddress clientIP = QHostAddress(pRequest->GetPeerAddress()); QHostAddress serverIP = QHostAddress(pRequest->GetHostAddress()); if (clientIP.protocol() == QAbstractSocket::IPv4Protocol) { serverVars.insert("IP_PROTOCOL", "IPv4"); } else if (clientIP.protocol() == QAbstractSocket::IPv6Protocol) { serverVars.insert("IP_PROTOCOL", "IPv6"); } if (((clientIP.protocol() == QAbstractSocket::IPv4Protocol) && (clientIP.isInSubnet(QHostAddress("172.16.0.0"), 12) || clientIP.isInSubnet(QHostAddress("192.168.0.0"), 16) || clientIP.isInSubnet(QHostAddress("10.0.0.0"), 8))) || ((clientIP.protocol() == QAbstractSocket::IPv6Protocol) && clientIP.isInSubnet(serverIP, 64))) // default subnet size is assumed to be /64 { serverVars.insert("CLIENT_NETWORK", "local"); } else { serverVars.insert("CLIENT_NETWORK", "remote"); } // ------------------------------------------------------------------ // Add the arrays (objects) we've just created to the global scope // They may be accessed as 'Server.REMOTE_ADDR' // ------------------------------------------------------------------ m_engine.globalObject().setProperty("Parameters", m_engine.toScriptValue(params)); m_engine.globalObject().setProperty("RequestHeaders", m_engine.toScriptValue(requestHeaders)); m_engine.globalObject().setProperty("Server", m_engine.toScriptValue(serverVars)); // ------------------------------------------------------------------ // Execute function to render output // ------------------------------------------------------------------ OutputStream outStream( pOutStream ); QScriptValueList args; args << m_engine.newQObject( &outStream ); args << m_engine.toScriptValue(params); QScriptValue ret = pInfo->m_oFunc.call( QScriptValue(), args ); if (ret.isError()) { QScriptValue lineNo = ret.property( "lineNumber" ); LOG(VB_GENERAL, LOG_ERR, QString("Error calling QSP File: %1(%2) - %3") .arg(sFileName) .arg( lineNo.toInt32 () ) .arg( ret .toString() )); Unlock(); return false; } if (m_engine.hasUncaughtException()) { LOG(VB_GENERAL, LOG_ERR, QString("Error calling QSP File: %1(%2) - %3") .arg(sFileName) .arg(m_engine.uncaughtExceptionLineNumber() ) .arg(m_engine.uncaughtException().toString())); Unlock(); return false; } Unlock(); } catch(...) { LOG(VB_GENERAL, LOG_ERR, QString("Exception while evaluating QSP File: %1") .arg(sFileName)); Unlock(); return false; } return true; }
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 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); }
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; }
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); }
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; }
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; }
void TabletServer::mainScreen(QTcpSocket *socket, const QStringList &path, const QStringMap &query) { Document * doc = mw->currentDocument(); if(!doc) { generic404(socket,path,query); return; } QStringList pathCopy = path; pathCopy.takeFirst(); // should be "tablet", but could be anything - /tablet/ is canonized for use in the tablet cache manifest for sfari QString control = pathCopy.isEmpty() ? "" : pathCopy.takeFirst().toLower(); //bool flag = pathCopy.isEmpty() ? 0 : pathCopy.takeFirst().toInt(); //qDebug() << "TabletServer::mainScreen(): control: "<<control; HttpUser *user = HttpUserUtil::instance()->currentUser(); if(control != "login") { if(!user) { QString from = QUrl::toPercentEncoding(toPathString(path,query).toAscii()).replace(" ", "+"); redirect(socket, "/tablet/login?from=" + from); return; } // I've decided to allow guests "view-only" access // else // if(user->level() == HttpUser::Guest) // { // Http_Send_Ok(socket) << "<html><head><title>Not Allowed</title></head><body><h1>Not Allowed</h1>Sorry, you're not allowed to access this site. (<a href='/tablet/login'>Login again</a>)</body></html"; // return; // } } if(control.isEmpty()) { SimpleTemplate tmpl("data/http/tablet.tmpl"); tmpl.param("user_name", user->user()); tmpl.param("user_level", (int)user->level()); tmpl.param("is_admin", user->level() == HttpUser::Admin); tmpl.param("is_user", user->level() == HttpUser::User); tmpl.param("is_guest", user->level() == HttpUser::Guest); // tmpl.param("list",outputGroupList); // // OutputControl * outputControl = mw->outputControl(liveId); // tmpl.param("black_toggled", outputControl->isBlackToggled()); // tmpl.param("clear_toggled", outputControl->isClearToggled()); // // SlideGroupViewControl *viewControl = mw->viewControl(liveId); // tmpl.param("qslide_toggled", viewControl->isQuickSlideToggled()); // // if(doc->filename().isEmpty()) // tmpl.param("docfile",tr("New File")); // else // tmpl.param("docfile",QFileInfo(doc->filename()).baseName()); // Http_Send_Ok(socket) << // "Content-Type: text/html\n\n" << // tmpl.toString(); QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "text/html"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << tmpl.toString(); } else if(control == "login") { loginPage(socket, path, query, "/tablet/login"); } else if(control == "list") { QString filter = query["filter"]; // Can be empty // Don't allow non-admins to search because it would interfere with the main UI if(!filter.isEmpty() && user->level() < HttpUser::Admin) { Http_Send_500txt(socket, "Not Authorized"); return; } QString mode = query["mode"]; // Either "db" or "file" bool pollingFlag = query["poll"] == "true"; QString clientMD5 = query["md5"]; // the md5 of the list contents to use to check for changes if pollingFlag == true // Compile list of results matching mode (from db or from current sched) and the filter, and return as json string // TODO add button to search online //qDebug() << "TabletServer::mainScreen(): list: mode: "<<mode<<", filter: "<<filter; QVariantMap result; QVariantList resultList; bool moreResults = false; int listCutoffLimit = 10; // included in results even though only relevant to 'db' mode // Buffer for compiling MD5 hash QStringList md5sigList; if(mode == "db") { bool isChanged = true; if(pollingFlag) { int currentChangeSequence = m_songListModel->currentChangeSequence(); QString seqString = QString::number(currentChangeSequence); // md5sigList is used to generate the md5 to send back to the client md5sigList << seqString; QString seqMd5 = MD5::md5sum(md5sigList.join("")); isChanged = false; if(seqMd5 != clientMD5) isChanged = true; } // Only regen list if 'isChanged' - and isChanged is only set to 'false' if: // - Client is in polling mode // - Client MD5 matches the MD5 of current sequence number // We do this because generating the list makes a call to filter() // which can cause trouble if the filter string is empty and the user // in the DViz main UI is trying to search for something (which would NOT change // the sequence number above, but would change the filter) if(isChanged) { // List cutoff limit only relevant when searching/quering database. // Cutoff not honored or implemented for file schedule QString maxResults = query["max"]; if(!maxResults.isEmpty()) listCutoffLimit = maxResults.toInt(); if(listCutoffLimit < 1) listCutoffLimit = 1; m_songListModel->filter(filter); moreResults = m_songListModel->rowCount() > listCutoffLimit; int resultCount = qMin(listCutoffLimit, m_songListModel->rowCount()); for(int i=0; i<resultCount; i++) { SongRecord *song = m_songListModel->songAt(i); if(!song) { qDebug() << "TabletServer::mainScreen(): list: db: No song at index: "<<i; continue; } QVariantMap line; line["id"] = song->songId(); line["title"] = song->title(); line["text"] = song->text(); line["arr"] = song->defaultArrangement()->arrangement().join(", "); resultList << line; // We use the sequence md5 (above) for the md5 sig instead of the list contents now // md5sigList.append(QString::number(song->songId())); // md5sigList.append(song->title()); // md5sigList.append(song->text()); } } } else { // int liveId = AppSettings::taggedOutput("live")->id(); // SlideGroup *liveGroup = mw->outputInst(liveId)->slideGroup(); DocumentListModel * model = mw->documentListModel(); //uint secs = QDateTime::currentDateTime().toTime_t(); QString lowerFilter = filter.toLower(); for(int idx = 0; idx < model->rowCount(); idx++) { SlideGroup * group = model->groupAt(idx); SongSlideGroup *songGroup = dynamic_cast<SongSlideGroup*>(group); if(songGroup && ( songGroup->groupTitle().toLower().contains(lowerFilter) || songGroup->text().toLower().contains(lowerFilter))) { QVariantMap row; QVariant tooltip = model->data(model->index(group->groupNumber(),0), Qt::ToolTipRole); QString viewText = group->assumedName(); if(tooltip.isValid()) viewText = tooltip.toString(); row["id"] = idx; //songGroup->groupId(); row["title"] = viewText; row["text"] = songGroup->text(); row["arr"] = songGroup->arrangement().join(", "); row["mapping"] = genArrMapping(songGroup->text(), songGroup->arrangement()); resultList << row; md5sigList.append(QString::number(songGroup->groupId())); md5sigList.append(viewText); md5sigList.append(songGroup->text()); } // We don't limit the number of results in the document results moreResults = false; } } QString currentMD5 = MD5::md5sum(md5sigList.join("")); bool isChanged = true; if(pollingFlag && currentMD5 == clientMD5) isChanged = false; if(isChanged) { result["num"] = resultList.size(); result["list"] = QVariant(resultList); result["more"] = moreResults; result["cutoff"] = listCutoffLimit; } else result["nochange"] = true; result["md5"] = currentMD5; QString jsonString = m_toJson.serialize(result); //qDebug() << "TabletServer::mainScreen(): list: result: "<<result; //qDebug() << "TabletServer::mainScreen(): list: json: "<<jsonString; // Http_Send_Ok(socket) << // "Content-Type: application/json\n\n" << // jsonString; QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "application/json"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << jsonString; } else if(control == "save_song") { if(user->level() < HttpUser::Admin) { Http_Send_500txt(socket, "Not Authorized"); return; } QString mode = query["mode"]; // Either "db" or "file" int itemid = query["itemid"].toInt(); // If mode is db, itemid is a songid, otherwise, it's a group index QString title = query["title"]; QString text = query["text"]; QString arrTxt = query["arr"]; QStringList newArrList = arrTxt.split(QRegExp("\\s*,\\s*")); SongRecord *song; if(mode == "file") { DocumentListModel * model = mw->documentListModel(); SlideGroup * group = model->groupAt(itemid); SongSlideGroup *songGroup = dynamic_cast<SongSlideGroup*>(group); // Update the document model songGroup->setArrangement(newArrList); songGroup->setGroupTitle(title); songGroup->setText(text); // automatically regenerates slides in document song = songGroup->song(); } else { song = SongRecord::retrieve(itemid); } if(!song) { Http_Send_404(socket) << "Invalid songid"; } song->setTitle(title); song->setText(text); SongArrangement *arr = song->defaultArrangement(); arr->setArrangement(newArrList); // Changes automatically committed to database QVariantMap result; result["mapping"] = genArrMapping(song->text(), arr->arrangement()); QString jsonString = m_toJson.serialize(result); QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "application/json"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << jsonString; } else if(control == "add_song") { if(user->level() < HttpUser::Admin) { Http_Send_500txt(socket, "Not Authorized"); return; } int songid = query["songid"].toInt(); QVariantMap result; SongRecord *song = SongRecord::retrieve(songid); if(!song) { Http_Send_404(socket) << "Invalid songid"; } else { SlideGroup *group = mw->songBrowser()->createSlideGroup(song); group->setGroupNumber(mw->currentDocument()->numGroups()); mw->currentDocument()->addGroup(group); result["groupnum"] = group->groupNumber(); } QString jsonString = m_toJson.serialize(result); QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "application/json"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << jsonString; } else if(control == "del_song") { if(user->level() < HttpUser::Admin) { Http_Send_500txt(socket, "Not Authorized"); return; } QString mode = query["mode"]; // Either "db" or "file" int itemid = query["itemid"].toInt(); if(mode == "file") { DocumentListModel * model = mw->documentListModel(); SlideGroup * group = model->groupAt(itemid); SongSlideGroup *songGroup = dynamic_cast<SongSlideGroup*>(group); if(!songGroup) { Http_Send_404(socket) << "Invalid songid"; } mw->currentDocument()->removeGroup(songGroup); } else { SongRecord *song = SongRecord::retrieve(itemid); if(!song) { Http_Send_404(socket) << "Invalid songid"; } SongRecord::deleteSong(song); } QVariantMap result; // Nothing to see here, move along. QString jsonString = m_toJson.serialize(result); QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "application/json"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << jsonString; } else if(control == "show_slide") { if(user->level() < HttpUser::User) { Http_Send_500txt(socket, "Not Authorized"); return; } int groupIdx = query["group"].toInt(); Document * doc = mw->currentDocument(); if(!doc) { generic404(socket,path,query); return; } if(groupIdx < 0 || groupIdx >= doc->numGroups()) { generic404(socket,path,query); return; } DocumentListModel * docModel = mw->documentListModel(); SlideGroup *group = docModel->groupAt(groupIdx); if(!group) { generic404(socket,path,query); return; } int liveId = AppSettings::taggedOutput("live")->id(); SlideGroup *liveGroup = mw->outputInst(liveId)->slideGroup(); Slide * liveSlide = mw->outputInst(liveId)->slide(); //SlideGroupViewControl *viewControl = mw->viewControl(liveId); //Slide * liveSlide = viewControl->selectedSlide(); int idx = query.value("slide").toInt(); if(idx < 0 || idx > group->numSlides()) { generic404(socket,path,query); return; } Slide *slide = group->at(idx); if(liveGroup != group || liveSlide != slide) mw->setLiveGroup(group, ! slide ? liveSlide : slide); // prevent changing slides when loading the group page if group already live on different slide if(liveGroup == group && liveSlide != slide/* && nextPathElement != "icon"*/) { // this is JUST a change slide request mw->setLiveGroup(liveGroup,slide); // 204 = HTTP No Content, ("...[the browser] SHOULD NOT change its document view...") Http_Send_Response(socket,"HTTP/1.0 204 Changed Slide") << ""; // BlackBerry Internet Browser doesnt honor HTTP 204, so we have to use javascript to make it not change the current document return; } else Http_Send_Response(socket,"HTTP/1.0 204 No Change") << ""; } else if(control == "poll_live_slide") { if(user->level() < HttpUser::Guest) { Http_Send_500txt(socket, "Not Authorized"); return; } DocumentListModel * docModel = mw->documentListModel(); QVariantMap result; bool ok = true; int liveId = AppSettings::taggedOutput("live")->id(); SlideGroup *liveGroup = mw->outputInst(liveId)->slideGroup(); Slide *liveSlide = mw->outputInst(liveId)->slide(); if(!liveGroup) { ok = false; result["error"] = "NLG"; } // SlideGroupViewControl *viewControl = mw->viewControl(liveId); // Slide * liveSlide = viewControl->selectedSlide(); if(!liveSlide && ok) { ok = false; result["error"] = "NLS"; } if(ok) { int groupIdx = docModel->indexForGroup(liveGroup).row(); int slideIdx = liveGroup->indexOf(liveSlide); result["groupIdx"] = groupIdx; result["slideIdx"] = slideIdx; } QString jsonString = m_toJson.serialize(result); QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "application/json"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << jsonString; } else { generic404(socket,path,query); } }
/** 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; }
QVariant MethodInfo::Invoke( Service *pService, const QStringMap &reqParams ) { HttpRedirectException exception; bool bExceptionThrown = false; QStringMap lowerParams; if (!pService) throw; // Change params to lower case for case-insensitive comparison QStringMap::const_iterator it = reqParams.begin(); for (; it != reqParams.end(); ++it) { lowerParams[it.key().toLower()] = *it; } // -------------------------------------------------------------- // Provide actual parameters received to method // -------------------------------------------------------------- pService->m_parsedParams = lowerParams.keys(); QList<QByteArray> paramNames = m_oMethod.parameterNames(); QList<QByteArray> paramTypes = m_oMethod.parameterTypes(); // ---------------------------------------------------------------------- // Create Parameter array (Can't have more than _MAX_PARAMS parameters).... // switched to static array for performance. // ---------------------------------------------------------------------- void *param[ _MAX_PARAMS ]; int types[ _MAX_PARAMS ]; memset( param, 0, _MAX_PARAMS * sizeof(void *)); memset( types, 0, _MAX_PARAMS * sizeof(int)); try { // -------------------------------------------------------------- // Add a place for the Return value // -------------------------------------------------------------- int nRetIdx = QMetaType::type( m_oMethod.typeName() ); if (nRetIdx != 0) { param[ 0 ] = QMetaType::create( nRetIdx ); types[ 0 ] = nRetIdx; } else { param[ 0 ] = nullptr; types[ 0 ] = 0; } // -------------------------------------------------------------- // Fill in parameters from request values // -------------------------------------------------------------- for( int nIdx = 0; nIdx < paramNames.length(); nIdx++ ) { QString sValue = lowerParams[ paramNames[ nIdx ].toLower() ]; QString sParamType = paramTypes[ nIdx ]; int nId = QMetaType::type( paramTypes[ nIdx ] ); void *pParam = nullptr; if (nId != 0) { pParam = QMetaType::create( nId ); } else { LOG(VB_GENERAL, LOG_ERR, QString("MethodInfo::Invoke - Type unknown '%1'") .arg(sParamType)); } types[nIdx+1] = nId; param[nIdx+1] = pService->ConvertToParameterPtr( nId, sParamType, pParam, sValue ); } #if 0 QThread *currentThread = QThread::currentThread(); QThread *objectThread = pService->thread(); if (currentThread == objectThread) LOG(VB_HTTP, LOG_DEBUG, "*** Threads are same ***"); else LOG(VB_HTTP, LOG_DEBUG, "*** Threads are Different!!! ***"); #endif pService->qt_metacall( QMetaObject::InvokeMetaMethod, m_nMethodIndex, param ); // -------------------------------------------------------------- // Delete param array, skip return parameter since not dynamically // created. // -------------------------------------------------------------- for (int nIdx=1; nIdx < paramNames.length()+1; nIdx++) { if ((types[ nIdx ] != 0) && (param[ nIdx ] != nullptr)) QMetaType::destroy( types[ nIdx ], param[ nIdx ] ); } } catch (QString &sMsg) { LOG(VB_GENERAL, LOG_ERR, QString("MethodInfo::Invoke - An Exception Occurred: %1") .arg(sMsg)); if ((types[ 0 ] != 0) && (param[ 0 ] != nullptr )) QMetaType::destroy( types[ 0 ], param[ 0 ] ); throw; } catch (HttpRedirectException &ex) { bExceptionThrown = true; exception = ex; } catch (...) { LOG(VB_GENERAL, LOG_INFO, "MethodInfo::Invoke - An Exception Occurred" ); } // -------------------------------------------------------------- // return the result after converting to a QVariant // -------------------------------------------------------------- QVariant vReturn; if ( param[ 0 ] != nullptr) { vReturn = pService->ConvertToVariant( types[ 0 ], param[ 0 ] ); if (types[ 0 ] != 0) QMetaType::destroy( types[ 0 ], param[ 0 ] ); } // -------------------------------------------------------------- // Re-throw exception if needed. // -------------------------------------------------------------- if (bExceptionThrown) throw exception; return vReturn; }
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 VpncSettingWidget::readConfig() { Q_D(VpncSettingWidget); // General settings QStringMap dataMap = d->setting->data(); // gateway QString gateway = dataMap[NM_VPNC_KEY_GATEWAY]; if (!gateway.isEmpty()) { d->ui.leGateway->setText(gateway); } // username QString user = dataMap[NM_VPNC_KEY_XAUTH_USER]; if (!user.isEmpty()) { d->ui.leUserName->setText(user); } // group name QString group = dataMap[NM_VPNC_KEY_ID]; if (!group.isEmpty()) { d->ui.leGroupName->setText(group); } // hybrid auth if (dataMap[NM_VPNC_KEY_AUTHMODE] == QLatin1String("hybrid")) { d->ui.cbUseHybridAuth->setChecked(true); d->ui.leCaCertPath->setUrl(KUrl(dataMap[NM_VPNC_KEY_CA_FILE])); } // password storage type is set in readSecrets // Optional settings // domain QString domain = dataMap[NM_VPNC_KEY_DOMAIN]; if (!domain.isEmpty()) { d->ui.leDomain->setText(domain); } // encryption if (dataMap[NM_VPNC_KEY_SINGLE_DES] == QLatin1String("yes")) { d->ui.cboEncryptionMethod->setCurrentIndex(VpncSettingWidgetPrivate::EnumEncryptionMethod::Weak); } else if (dataMap[NM_VPNC_KEY_NO_ENCRYPTION] == QLatin1String("yes")) { d->ui.cboEncryptionMethod->setCurrentIndex(VpncSettingWidgetPrivate::EnumEncryptionMethod::None); } // nat traversal if (dataMap[NM_VPNC_KEY_NAT_TRAVERSAL_MODE] == NM_VPNC_NATT_MODE_NATT) d->ui.cboNatTraversal->setCurrentIndex(VpncSettingWidgetPrivate::EnumNatt::NattIfAvail); else if (dataMap[NM_VPNC_KEY_NAT_TRAVERSAL_MODE] == NM_VPNC_NATT_MODE_NATT_ALWAYS) d->ui.cboNatTraversal->setCurrentIndex(VpncSettingWidgetPrivate::EnumNatt::Force); else if (dataMap[NM_VPNC_KEY_NAT_TRAVERSAL_MODE] == NM_VPNC_NATT_MODE_CISCO) d->ui.cboNatTraversal->setCurrentIndex(VpncSettingWidgetPrivate::EnumNatt::CiscoUdp); else if (dataMap[NM_VPNC_KEY_NAT_TRAVERSAL_MODE] == NM_VPNC_NATT_MODE_NONE) d->ui.cboNatTraversal->setCurrentIndex(VpncSettingWidgetPrivate::EnumNatt::Disabled); // dead peer detection if (dataMap.contains(NM_VPNC_KEY_DPD_IDLE_TIMEOUT)) { uint dpdTimeout = dataMap.value(NM_VPNC_KEY_DPD_IDLE_TIMEOUT).toUInt(); if (dpdTimeout == 0) { d->ui.chkDeadPeerDetection->setChecked(false); d->dpdTimeout = dpdTimeout; } } // dh group if (dataMap.contains(NM_VPNC_KEY_DHGROUP)) { QString dhGroup = dataMap.value(NM_VPNC_KEY_DHGROUP); if (dhGroup == NM_VPNC_DHGROUP_DH1) { // DH Group 1 d->ui.cboDHGroup->setCurrentIndex(VpncSettingWidgetPrivate::EnumDh::Dh1); } else if (dhGroup == NM_VPNC_DHGROUP_DH2) { // DH Group 2 d->ui.cboDHGroup->setCurrentIndex(VpncSettingWidgetPrivate::EnumDh::Dh2); } else if (dhGroup == NM_VPNC_DHGROUP_DH5) { // DH Group 5 d->ui.cboDHGroup->setCurrentIndex(VpncSettingWidgetPrivate::EnumDh::Dh5); } } // Perfect Forward Secrecy if (dataMap.contains(NM_VPNC_KEY_PERFECT_FORWARD)) { QString forwardSecrecy = dataMap.value(NM_VPNC_KEY_PERFECT_FORWARD); if (forwardSecrecy == QLatin1String("nopfs")) { d->ui.cboPerfectForwardSecrecy->setCurrentIndex(VpncSettingWidgetPrivate::EnumPerfectForwardSecrecy::NoPfs); } else if (forwardSecrecy == QLatin1String("server")) { d->ui.cboPerfectForwardSecrecy->setCurrentIndex(VpncSettingWidgetPrivate::EnumPerfectForwardSecrecy::Server); } else if (forwardSecrecy == QLatin1String("dh1")) { d->ui.cboPerfectForwardSecrecy->setCurrentIndex(VpncSettingWidgetPrivate::EnumPerfectForwardSecrecy::Dh1); } else if (forwardSecrecy == QLatin1String("dh2")) { d->ui.cboPerfectForwardSecrecy->setCurrentIndex(VpncSettingWidgetPrivate::EnumPerfectForwardSecrecy::Dh2); } else if (forwardSecrecy == QLatin1String("dh5")) { d->ui.cboPerfectForwardSecrecy->setCurrentIndex(VpncSettingWidgetPrivate::EnumPerfectForwardSecrecy::Dh5); } } // Vendor if (dataMap.contains(NM_VPNC_KEY_VENDOR)) { QString vendor = dataMap.value(NM_VPNC_KEY_VENDOR); if (vendor == QLatin1String("cisco")) { d->ui.cboVendor->setCurrentIndex(VpncSettingWidgetPrivate::EnumVendor::Cisco); } else if (vendor == QLatin1String("netscreen")) { d->ui.cboVendor->setCurrentIndex(VpncSettingWidgetPrivate::EnumVendor::Netscreen); } } // Application Version if (dataMap.contains(NM_VPNC_KEY_APP_VERSION)) { d->ui.leApplicationVersion->setText(dataMap.value(NM_VPNC_KEY_APP_VERSION)); } // Local Port if (dataMap.contains(NM_VPNC_KEY_LOCAL_PORT)) { d->ui.spbLocalPort->setValue(dataMap.value(NM_VPNC_KEY_LOCAL_PORT).toInt()); } // Cisco UDP Encapsulation Port if (dataMap.contains(NM_VPNC_KEY_CISCO_UDP_ENCAPS_PORT)) { d->ui.spbCiscoUdpEncPort->setValue(dataMap.value(NM_VPNC_KEY_CISCO_UDP_ENCAPS_PORT).toInt()); } }
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); }
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; }