void OpenLinksFromFileSystem::AnchorClicked(const QUrl & url) { #ifdef Q_OS_WIN if(url.host().contains("shelexecute")) { QUrlQuery q; q.setQuery(url.query()); QString cmd = q.queryItemValue("cmd",QUrl::FullyDecoded); QString arg = q.queryItemValue("arg",QUrl::FullyDecoded); LPCWSTR s1 = (LPCWSTR)cmd.utf16(); LPCWSTR s2 = NULL; if(q.hasQueryItem("arg")) s2 = (LPCWSTR)arg.utf16(); ShellExecute(NULL,NULL,s1,s2,NULL,SW_RESTORE); }else #endif { QFileInfo info(url.toString()); QDesktopServices::openUrl(QUrl::fromLocalFile(info.absoluteFilePath())); } }
/*! * Image { * source: "image://avatar/path?name=icon-name" * } * * Image { * source: "image://avatar/path?size=64&name=icon-name" * } */ QPixmap QuickAvatarProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) { const QUrl url(QStringLiteral("file:///") + id); const QUrlQuery query(url.query()); const QString filePath = url.path(); const QString iconName = query.queryItemValue(QStringLiteral("name")); const QString iconSize = query.queryItemValue(QStringLiteral("size")); QSize tmp; if (!size) size = &tmp; bool ok = false; int iconSizeValue = iconSize.toInt(&ok); if (ok) *size = QSize(iconSizeValue, iconSizeValue); else if (requestedSize.width() > 0) *size = requestedSize; else *size = QSize(128, 128); QIcon icon = Icon(iconName); if (filePath.size() > 1) icon = AvatarFilter::icon(filePath, icon); return icon.pixmap(*size); }
void Utils::testIncludeUrlParams() { QUrl urla(QString("http://example.com")); QHash<QString, QString> params; params.insert("simple", "c"); params.insert("withspecial", "a?b"); params.insert("withspace", "a b"); params.insert("username", "a123fx b"); params.insert("password", "!@#+-$%^12&*()qweqesaf\"';`~"); params.insert("withplus", "a+b"); QUrl urlb = ::includeQueryParams(urla, params); QVERIFY(urla.scheme() == urlb.scheme()); QVERIFY(urla.host() == urlb.host()); Q_FOREACH (const QString& key, params.keys()) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) QString encoded_key = QUrl::toPercentEncoding(key); QString encoded_value = QUrl::toPercentEncoding(params[encoded_key]); QUrlQuery query = QUrlQuery(urlb.query()); QVERIFY(query.queryItemValue(encoded_key, QUrl::FullyEncoded) == encoded_value); #else QVERIFY(urlb.queryItemValue(key) == params[key]); #endif } }
bool OpenLocalHelper::openLocalFile(const QUrl &url) { if (url.scheme() != kSeafileProtocolScheme) { qWarning("[OpenLocalHelper] unknown scheme %s\n", url.scheme().toUtf8().data()); return false; } if (url.host() != kSeafileProtocolHostOpenFile) { qWarning("[OpenLocalHelper] unknown command %s\n", url.host().toUtf8().data()); return false; } #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QUrlQuery url_query = QUrlQuery(url.query()); QString repo_id = url_query.queryItemValue("repo_id", QUrl::FullyDecoded); QString email = url_query.queryItemValue("email", QUrl::FullyDecoded); QString path = url_query.queryItemValue("path", QUrl::FullyDecoded); #else QString repo_id = url.queryItemValue("repo_id"); QString email = url.queryItemValue("email"); QString path = url.queryItemValue("path"); #endif if (repo_id.size() < 36) { qWarning("[OpenLocalHelper] invalid repo_id %s\n", repo_id.toUtf8().data()); return false; } qDebug("[OpenLocalHelper] open local file: repo %s, path %s\n", repo_id.toUtf8().data(), path.toUtf8().data()); RepoService::instance()->openLocalFile(repo_id, path); return true; }
void RequestParameters::parseUrl(const QUrl & url) { if (!url.hasQuery()) { return; } QList<QPair<QString, QVariant >> parameters; for (const QString & parameter : url.query().split('&')) { int splitIndex = parameter.indexOf('='); if (splitIndex<=0) { continue; } QString key = parameter.left(splitIndex); QString value = parameter.mid(splitIndex + 1); parameters << QPair<QString, QVariant>(key, value); } parseList(parameters); }
/*! Constructs a QUrlQuery object and parses the query string found in the \a url URL, using the default query delimiters. To parse a query string using other delimiters, you should first set them using setQueryDelimiters() and then set the query with setQuery(). \sa QUrl::query() */ QUrlQuery::QUrlQuery(const QUrl &url) : d(0) { // use internals to avoid unnecessary recoding // ### FIXME: actually do it if (url.hasQuery()) d = new QUrlQueryPrivate(url.query()); }
bool HTTPManager::handleHTTPRequest(HTTPConnection* connection, const QUrl& url, bool skipSubHandler) { if (!skipSubHandler && requestHandledByRequestHandler(connection, url)) { // this request was handled by our request handler object // so we don't need to attempt to do so in the document root return true; } if (!_documentRoot.isEmpty()) { // check to see if there is a file to serve from the document root for this path QString subPath = url.path(); // remove any slash at the beginning of the path if (subPath.startsWith('/')) { subPath.remove(0, 1); } QString filePath; if (QFileInfo(_documentRoot + subPath).isFile()) { filePath = _documentRoot + subPath; } else if (subPath.size() > 0 && !subPath.endsWith('/')) { // this could be a directory with a trailing slash // send a redirect to the path with a slash so we can QString redirectLocation = '/' + subPath + '/'; if (!url.query().isEmpty()) { redirectLocation += "?" + url.query(); } QHash<QByteArray, QByteArray> redirectHeader; redirectHeader.insert(QByteArray("Location"), redirectLocation.toUtf8()); connection->respond(HTTPConnection::StatusCode301, "", HTTPConnection::DefaultContentType, redirectHeader); } // if the last thing is a trailing slash then we want to look for index file if (subPath.endsWith('/') || subPath.size() == 0) { QStringList possibleIndexFiles = QStringList() << "index.html" << "index.shtml"; foreach (const QString& possibleIndexFilename, possibleIndexFiles) { if (QFileInfo(_documentRoot + subPath + possibleIndexFilename).exists()) { filePath = _documentRoot + subPath + possibleIndexFilename; break; } } }
/** Compute MD5 signature using url queries keys and values following Flickr notice: http://www.flickr.com/services/api/auth.spec.html */ QString FlickrTalker::getApiSig(const QString& secret, const QUrl& url) { QUrlQuery urlQuery(url.query()); QList<QPair<QString, QString> > temp_queries = urlQuery.queryItems(); QMap<QString, QString> queries; QPair<QString, QString> pair; foreach(pair, temp_queries) { queries.insert(pair.first,pair.second); }
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // return if URI is not valid or is no sapcoin URI if(!uri.isValid() || uri.scheme() != QString("sapcoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) QUrlQuery q; q.setQuery(uri.query()); QList<QPair<QString, QString> > items = q.queryItems(); #else QList<QPair<QString, QString> > items = uri.queryItems(); #endif for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::SAP, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; }
QUrl ItemFields::toUrl() const { if (isRemote()) { QUrl url = QUrl(path().toString()); switch(dataType()) { case dt_web_sc: { if (url.query().isEmpty()) // links with hashed policy should not be attachable for additional fields - this action broke policy url.setQuery(Web::Soundcloud::Queries::obj().genDefaultParams()); break;} default:; } return url; } else return QUrl::fromLocalFile(fullPath()); }
void HttpPoll::connectToHost(const QString &proxyHost, int proxyPort, const QUrl &url) { resetConnection(true); bool useSsl = false; d->port = 80; // using proxy? if(!proxyHost.isEmpty()) { d->host = proxyHost; d->port = proxyPort; d->url = url; d->use_proxy = true; } else { d->host = url.host(); if(url.port() != -1) d->port = url.port(); else if (url.scheme() == "https") { d->port = 443; useSsl = true; } #if QT_VERSION < 0x050000 d->url = url.path() + "?" + url.encodedQuery(); #else d->url.setUrl(url.path() + "?" + url.query(QUrl::FullyEncoded), QUrl::StrictMode); #endif d->use_proxy = false; } resetKey(); bool last; QString key = getKey(&last); #ifdef PROX_DEBUG fprintf(stderr, "HttpPoll: Connecting to %s:%d [%s]", d->host.latin1(), d->port, d->url.latin1()); if(d->user.isEmpty()) fprintf(stderr, "\n"); else fprintf(stderr, ", auth {%s,%s}\n", d->user.latin1(), d->pass.latin1()); #endif QPointer<QObject> self = this; syncStarted(); if(!self) return; d->state = 1; d->http.setUseSsl(useSsl); d->http.setAuth(d->user, d->pass); d->http.post(d->host, d->port, d->url, makePacket("0", key, "", QByteArray()), d->use_proxy); }
QString QzTools::urlEncodeQueryString(const QUrl &url) { QString returnString = url.toString(QUrl::RemoveQuery | QUrl::RemoveFragment); if (url.hasQuery()) { returnString += QLatin1Char('?') + url.query(QUrl::FullyEncoded); } if (url.hasFragment()) { returnString += QLatin1Char('#') + url.fragment(QUrl::FullyEncoded); } returnString.replace(QLatin1Char(' '), QLatin1String("%20")); return returnString; }
void DeckStatsInterface::getAnalyzeRequestData(DeckList *deck, QByteArray *data) { DeckList deckWithoutTokens; copyDeckWithoutTokens(*deck, deckWithoutTokens); #if QT_VERSION < 0x050000 QUrl params; params.addQueryItem("deck", deckWithoutTokens.writeToString_Plain()); data->append(params.encodedQuery()); #else QUrl params; QUrlQuery urlQuery; urlQuery.addQueryItem("deck", deckWithoutTokens.writeToString_Plain()); params.setQuery(urlQuery); data->append(params.query(QUrl::EncodeReserved)); #endif }
/** * Checks if connection parameters have changed. * If it it, close the current connection */ void kio_sieveProtocol::changeCheck(const QUrl &url) { QString auth; // Check the SASL auth mechanism in the 'sasl' metadata... if (!metaData(QStringLiteral("sasl")).isEmpty()) { auth = metaData(QStringLiteral("sasl")).toUpper(); } else { // ... and if not found, check the x-mech=AUTH query part of the url. QString query = url.query(); if (query.startsWith(QLatin1Char('?'))) { query.remove(0, 1); } QStringList q = query.split(QLatin1Char(',')); QStringList::iterator it; for (it = q.begin(); it != q.end(); ++it) { if (((*it).section(QLatin1Char('='), 0, 0)).toLower() == QLatin1String("x-mech")) { auth = ((*it).section(QLatin1Char('='), 1)).toUpper(); break; } } } ksDebug << "auth: " << auth << " m_sAuth: " << m_sAuth << endl; if (m_sAuth != auth) { m_sAuth = auth; if (isConnected()) { disconnect(); } } // For TLS, only disconnect if we are unencrypted and are // no longer allowed (otherwise, it's still fine): const bool allowUnencryptedNow = QUrlQuery(url).queryItemValue(QStringLiteral("x-allow-unencrypted")) == QLatin1String("true"); if (m_allowUnencrypted && !allowUnencryptedNow) { if (isConnected()) { disconnect(); } } m_allowUnencrypted = allowUnencryptedNow; }
BtsApiNotifier *BtsApi::setFolderHosts(const QString &secret, const QStringList &hosts) { QueryList ql; ql << QueryPair("secret", secret) << QueryPair("hosts", hosts.join(',')); QUrl apiUrl = getApiUrl(p, "set_folder_hosts", ql); QString queryString = apiUrl.query(QUrl::FullyEncoded); QNetworkReply *reply = p->nam->get(QNetworkRequest(apiUrl)); BtsApiNotifier *notifier = new BtsApiNotifier(this); connect(reply, &QNetworkReply::finished, [this, reply, notifier, secret]() { notifier->deleteLater(); if(checkForError(reply, notifier)) return; QJsonDocument doc = QJsonDocument::fromJson(reply->readAll()); if(checkForError(doc, notifier)) return; QJsonObject obj = doc.object(); QJsonArray arr = obj.value("hosts").toArray(); QStringList res; for(const QJsonValue &val: arr) res << val.toString(); emit setFolderHostsResult(res, secret); emit notifier->setFolderHostsResult(res, secret); }); return notifier; }
QUrl WmsServerLayout::downloadUrl( const QUrl &prototypeUrl, const Marble::TileId &tileId ) const { GeoDataLatLonBox box = tileId.toLatLonBox( m_textureLayer ); #if QT_VERSION < 0x050000 QUrl url = prototypeUrl; #else QUrlQuery url(prototypeUrl.query()); #endif url.addQueryItem( "service", "WMS" ); url.addQueryItem( "request", "GetMap" ); url.addQueryItem( "version", "1.1.1" ); if ( !url.hasQueryItem( "styles" ) ) url.addQueryItem( "styles", "" ); if ( !url.hasQueryItem( "format" ) ) { if ( m_textureLayer->fileFormat().toLower() == "jpg" ) url.addQueryItem( "format", "image/jpeg" ); else url.addQueryItem( "format", "image/" + m_textureLayer->fileFormat().toLower() ); } if ( !url.hasQueryItem( "srs" ) ) { url.addQueryItem( "srs", epsgCode() ); } if ( !url.hasQueryItem( "layers" ) ) url.addQueryItem( "layers", m_textureLayer->name() ); url.addQueryItem( "width", QString::number( m_textureLayer->tileSize().width() ) ); url.addQueryItem( "height", QString::number( m_textureLayer->tileSize().height() ) ); url.addQueryItem( "bbox", QString( "%1,%2,%3,%4" ).arg( QString::number( box.west( GeoDataCoordinates::Degree ), 'f', 12 ) ) .arg( QString::number( box.south( GeoDataCoordinates::Degree ), 'f', 12 ) ) .arg( QString::number( box.east( GeoDataCoordinates::Degree ), 'f', 12 ) ) .arg( QString::number( box.north( GeoDataCoordinates::Degree ), 'f', 12 ) ) ); #if QT_VERSION < 0x050000 return url; #else QUrl finalUrl = prototypeUrl; finalUrl.setQuery(url); return finalUrl; #endif }
void Authorization::handleChangedUrl(QUrl const& newUrl) { static QUrl const uAuthtorizationRedirectUrl(AUTHORIZATION_REDIRECT_URL); if(newUrl.matches(uAuthtorizationRedirectUrl,QUrl::RemoveFragment | QUrl::RemoveQuery)) { if( newUrl.hasFragment() ) { QUrlQuery query( newUrl.fragment() ); QString accessToken = query.queryItemValue(QString("access_token")); QString userID = query.queryItemValue("user_id"); emit success(accessToken,userID); } else { QUrlQuery query( newUrl.query() ); QString error = query.queryItemValue(QString("error")); QString errorDescription = query.queryItemValue("eror_description"); emit failure(error,errorDescription); } hide(); } }
int ZnsHelper::openSession(const SourceT& srcInfo) { setBaseUrl(srcInfo.mon_url); QStringList authInfo = ngrt4n::getAuthInfo(srcInfo.auth); if (authInfo.size() != 2) { m_lastError = tr("Bad auth string, should be in the form of login:password"); return -1; } setBaseUrl(srcInfo.mon_url); #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QUrl params; #else QUrlQuery params; #endif params.addQueryItem("__ac_name", authInfo[0]); params.addQueryItem("__ac_password", authInfo[1]); params.addQueryItem("submitted", "true"); params.addQueryItem("came_from", getApiContextEndpoint()); setSslPeerVerification(srcInfo.verify_ssl_peer != 0); QNetworkReply* response = NULL; #if QT_VERSION < QT_VERSION_CHECK(5,0,0) response = postRequest(ZnsHelper::Login, params.encodedQuery()); #else response = postRequest(ZnsHelper::Login, params.query(QUrl::FullyEncoded).toUtf8()); #endif if (! response || processLoginReply(response) != 0) { return -1; } return 0; }
QString QzTools::urlEncodeQueryString(const QUrl &url) { QString returnString = url.toString(QUrl::RemoveQuery | QUrl::RemoveFragment); if (url.hasQuery()) { #if QT_VERSION >= 0x050000 returnString += QLatin1Char('?') + url.query(QUrl::FullyEncoded); #else returnString += QLatin1Char('?') + url.encodedQuery(); #endif } if (url.hasFragment()) { #if QT_VERSION >= 0x050000 returnString += QLatin1Char('#') + url.fragment(QUrl::FullyEncoded); #else returnString += QLatin1Char('#') + url.encodedFragment(); #endif } returnString.replace(QLatin1Char(' '), QLatin1String("%20")); return returnString; }
bool KWebKitPart::openUrl(const QUrl &_u) { QUrl u (_u); kDebug() << u; // Ignore empty requests... if (u.isEmpty()) return false; // If the URL given is a supported local protocol, e.g. "bookmark" but lacks // a path component, we set the path to "/" here so that the security context // will properly allow access to local resources. if (u.host().isEmpty() && u.path().isEmpty() && KProtocolInfo::protocolClass(u.scheme()) == QL1S(":local")) { u.setPath(QL1S("/")); } // Do not emit update history when url is typed in since the embedding part // should handle that automatically itself. At least Konqueror does that. m_emitOpenUrlNotify = false; // Pointer to the page object... WebPage* p = page(); Q_ASSERT(p); // Handle error conditions... if (u.scheme() == QL1S("error")) { /** * The format of the error url is that two variables are passed in the query: * error = int kio error code, errText = QString error text from kio * and the URL where the error happened is passed as a sub URL. */ const QUrl mainUrl(u.fragment()); if (mainUrl.isValid()) { QString query = u.query(QUrl::FullyDecoded); QRegularExpression pattern("error=(\\d+)&errText=(.*)"); QRegularExpressionMatch match = pattern.match(query); int error = match.captured(1).toInt(); // error=0 isn't a valid error code, so 0 means it's missing from the URL if (error == 0) { error = KIO::ERR_UNKNOWN; } const QString errorText = match.captured(2); emit m_browserExtension->setLocationBarUrl(mainUrl.toDisplayString()); if (p) { m_webView->setHtml(p->errorPage(error, errorText, mainUrl)); return true; } } return false; } KParts::BrowserArguments bargs (m_browserExtension->browserArguments()); KParts::OpenUrlArguments args (arguments()); if (u != *globalBlankUrl) { // Get the SSL information sent, if any... if (args.metaData().contains(QL1S("ssl_in_use"))) { WebSslInfo sslInfo; sslInfo.restoreFrom(KIO::MetaData(args.metaData()).toVariant()); sslInfo.setUrl(u); p->setSslInfo(sslInfo); } } // Set URL in KParts before emitting started; konq plugins rely on that. setUrl(u); m_doLoadFinishedActions = true; m_webView->loadUrl(u, args, bargs); return true; }
int main(int argc, char **argv) { #if (QT_VERSION < 0x050200) #error("You need Qt 5.2.0 or later to compile Actiona Executer"); #endif #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) QtSingleApplication app("actiona-exec", argc, argv); #else ActionTools::NativeEventFilteringApplication app("actiona-exec", argc, argv); #endif app.setQuitOnLastWindowClosed(false); qAddPostRoutine(cleanup); qsrand(std::time(NULL)); #ifdef Q_OS_LINUX notify_init("Actiona executer"); #endif #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); #endif QxtCommandOptions preOptions; preOptions.add("portable", QObject::tr("starts in portable mode, storing the settings in the executable folder")); preOptions.alias("portable", "p"); preOptions.parse(QCoreApplication::arguments()); if(preOptions.count("portable") > 0) { QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, QApplication::applicationDirPath() + "/userSettings"); QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, QApplication::applicationDirPath() + "/systemSettings"); QSettings::setDefaultFormat(QSettings::IniFormat); } QString locale = Tools::locale(); Tools::installQtTranslator(locale); Tools::installTranslator("tools", locale); Tools::installTranslator("actiontools", locale); Tools::installTranslator("executer", locale); Tools::installTranslator("actexecuter", locale); const QStringList &arguments = QCoreApplication::arguments(); QxtCommandOptions options; options.setFlagStyle(QxtCommandOptions::DoubleDash); options.setScreenWidth(0); options.add("code", QObject::tr("switch to code mode, may not be used with -s")); options.alias("code", "c"); options.add("script", QObject::tr("switch to script mode, may not be used with -c")); options.alias("script", "s"); options.add("nocodeqt", QObject::tr("do not include the Qt library into the code")); options.alias("nocodeqt", "Q"); options.add("portable", QObject::tr("starts in portable mode, storing the settings in the executable folder")); options.alias("portable", "p"); options.add("proxy-mode", QObject::tr("sets the proxy mode, values are \"none\", \"system\" (default) or \"custom\"")); options.add("proxy-type", QObject::tr("sets the custom proxy type, values are \"http\" or \"socks\" (default)")); options.add("proxy-host", QObject::tr("sets the custom proxy host")); options.add("proxy-port", QObject::tr("sets the custom proxy port")); options.add("proxy-user", QObject::tr("sets the custom proxy user")); options.add("proxy-password", QObject::tr("sets the custom proxy password")); #ifdef Q_OS_WIN options.add("console", QObject::tr("create a console to see debug output")); options.add("pause-at-end", QObject::tr("wait for user input at the end of the execution, used only with --console")); #endif options.add("version", QObject::tr("show the program version")); options.alias("version", "v"); options.add("help", QObject::tr("show this help text")); options.alias("help", "h"); options.parse(arguments); #ifdef Q_OS_WIN if(options.count("console")) { createConsole(); if(options.count("pause-at-end")) qAddPostRoutine(pause); } #endif qRegisterMetaType<ActionTools::ActionInstance>("ActionInstance"); qRegisterMetaType<ActionTools::ActionException::Exception>("Exception"); qRegisterMetaType<ActionTools::Parameter>("Parameter"); qRegisterMetaType<ActionTools::SubParameter>("SubParameter"); qRegisterMetaType<Tools::Version>("Version"); qRegisterMetaTypeStreamOperators<ActionTools::ActionInstance>("ActionInstance"); qRegisterMetaTypeStreamOperators<ActionTools::Parameter>("Parameter"); qRegisterMetaTypeStreamOperators<ActionTools::SubParameter>("SubParameter"); qRegisterMetaTypeStreamOperators<Tools::Version>("Version"); if(options.count("version")) { QTextStream stream(stdout); stream << "Actiona Executer version " << Global::ACTIONA_VERSION.toString() << ", script version " << Global::SCRIPT_VERSION.toString() << "\n"; stream.flush(); return 0; } if(options.count("help") || options.showUnrecognizedWarning() || options.positional().count() < 1 || (options.count("code") && options.count("script"))) { QTextStream stream(stdout); stream << QObject::tr("usage: ") << QCoreApplication::arguments().at(0) << " " << QObject::tr("[parameters]") << " " << QObject::tr("filename") << "\n"; stream << QObject::tr("Parameters are:") << "\n"; stream << options.getUsage(); stream.flush(); return -1; } app.addLibraryPath(QApplication::applicationDirPath() + "/actions"); app.addLibraryPath(QApplication::applicationDirPath() + "/plugins"); if(!options.count("nocodeqt")) app.addLibraryPath(QApplication::applicationDirPath() + "/code"); #ifdef Q_OS_LINUX { #ifdef ACT_PROFILE Tools::HighResolutionTimer timer("Load key codes"); #endif ActionTools::KeySymHelper::loadKeyCodes(); } #endif // Proxy settings int proxyMode = ActionTools::Settings::PROXY_SYSTEM; if(options.value("proxy-mode").toString() == "none") proxyMode = ActionTools::Settings::PROXY_NONE; else if(options.value("proxy-mode").toString() == "custom") proxyMode = ActionTools::Settings::PROXY_CUSTOM; else if(options.value("proxy-mode").toString() == "system") proxyMode = ActionTools::Settings::PROXY_SYSTEM; else if(!options.value("proxy-mode").toString().isEmpty()) { QTextStream stream(stdout); stream << QObject::tr("Unknown proxy mode, values are \"none\", \"system\" (default) or \"custom\"") << "\n"; stream.flush(); return -1; } QNetworkProxy proxy; switch(proxyMode) { case ActionTools::Settings::PROXY_NONE: proxy.setType(QNetworkProxy::NoProxy); break; case ActionTools::Settings::PROXY_SYSTEM: { QUrl url(Global::CONNECTIVITY_URL); QNetworkProxyQuery networkProxyQuery(url); QList<QNetworkProxy> listOfProxies = QNetworkProxyFactory::systemProxyForQuery(networkProxyQuery); if(!listOfProxies.isEmpty()) proxy = listOfProxies.first(); else proxy.setType(QNetworkProxy::NoProxy); } break; case ActionTools::Settings::PROXY_CUSTOM: { int type = ActionTools::Settings::PROXY_TYPE_SOCKS5; if(options.value("proxy-type").toString() == "http") type = ActionTools::Settings::PROXY_TYPE_HTTP; else if(options.value("proxy-type").toString() == "socks") type = ActionTools::Settings::PROXY_TYPE_SOCKS5; else if(!options.value("proxy-type").toString().isEmpty()) { QTextStream stream(stdout); stream << QObject::tr("Unknown proxy type, values are \"http\" or \"socks\" (default)") << "\n"; stream.flush(); return -1; } QNetworkProxy proxy; if(type == ActionTools::Settings::PROXY_TYPE_HTTP) proxy.setType(QNetworkProxy::HttpProxy); else proxy.setType(QNetworkProxy::Socks5Proxy); proxy.setHostName(options.value("proxy-host").toString()); proxy.setPort(options.value("proxy-port").toInt()); proxy.setUser(options.value("proxy-user").toString()); proxy.setPassword(options.value("proxy-password").toString()); } break; } QNetworkProxy::setApplicationProxy(proxy); QUrl protocolUrl = QUrl::fromEncoded(arguments.at(1).toUtf8()); if(protocolUrl.isValid() && protocolUrl.scheme() != "actiona") protocolUrl = QUrl(); MainClass::ExecutionMode executionMode = MainClass::Unknown; MainClass mainClass; if(protocolUrl.isValid()) { QString mode; using QStringPair = QPair<QString, QString>; #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) for(const QStringPair &queryItem: QUrlQuery(protocolUrl.query()).queryItems()) #else for(const QStringPair &queryItem: protocolUrl.queryItems()) #endif { if(queryItem.first == "mode") { mode = queryItem.second; break; } } if(mode == "code") executionMode = MainClass::Code; else if(mode == "script") executionMode = MainClass::Script; else { if(protocolUrl.path().endsWith(".ascr")) executionMode = MainClass::Script; else if(protocolUrl.path().endsWith(".acod")) executionMode = MainClass::Code; else { QTextStream stream(stdout); stream << QObject::tr("Unknown execution mode, please specify mode=script or mode=code") << "\n"; stream.flush(); return -1; } } if(!mainClass.start(executionMode, protocolUrl)) return -1; } else { QString filename = options.positional().at(0); if(options.count("code")) executionMode = MainClass::Code; else if(options.count("script")) executionMode = MainClass::Script; else { if(filename.endsWith(".ascr")) executionMode = MainClass::Script; else if(filename.endsWith(".acod")) executionMode = MainClass::Code; else { QTextStream stream(stdout); stream << QObject::tr("Unknown execution mode, please specify -s (script) or -c (code)") << "\n"; stream.flush(); return -1; } } QFile file(filename); if(!file.open(QIODevice::ReadOnly)) { QTextStream stream(stdout); stream << QObject::tr("Unable to read input file") << "\n"; stream.flush(); return -1; } if(!mainClass.start(executionMode, &file, file.fileName())) { file.close(); return -1; } } return app.exec(); }
int64_t Downloader::downloadWin(Job* job, const Request& request, Downloader::Response* response) { QUrl url = request.url; QString verb = request.httpMethod; QFile* file = request.file; QString* mime = &response->mimeType; QString* contentDisposition = &response->contentDisposition; HWND parentWindow = defaultPasswordWindow; QString* sha1 = &response->hashSum; bool useCache = request.useCache; QCryptographicHash::Algorithm alg = request.alg; bool keepConnection = request.keepConnection; int timeout = request.timeout; bool interactive = request.interactive; QString initialTitle = job->getTitle(); job->setTitle(initialTitle + " / " + QObject::tr("Connecting")); if (sha1) sha1->clear(); QString server = url.host(); QString resource = url.path(); QString encQuery = url.query(QUrl::FullyEncoded); if (!encQuery.isEmpty()) resource.append('?').append(encQuery); QString agent("Npackd/"); agent.append(NPACKD_VERSION); agent += " (compatible; MSIE 9.0)"; HINTERNET internet = InternetOpenW((WCHAR*) agent.utf16(), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0); if (internet == 0) { QString errMsg; WPMUtils::formatMessage(GetLastError(), &errMsg); job->setErrorMessage(errMsg); } if (job->shouldProceed()) { // change the timeout to 5 minutes DWORD rec_timeout = timeout * 1000; InternetSetOption(internet, INTERNET_OPTION_RECEIVE_TIMEOUT, &rec_timeout, sizeof(rec_timeout)); // enable automatic gzip decoding const DWORD INTERNET_OPTION_HTTP_DECODING = 65; BOOL b = TRUE; InternetSetOption(internet, INTERNET_OPTION_HTTP_DECODING, &b, sizeof(b)); job->setProgress(0.01); } HINTERNET hConnectHandle = 0; if (job->shouldProceed()) { INTERNET_PORT port = url.port(url.scheme() == "https" ? INTERNET_DEFAULT_HTTPS_PORT: INTERNET_DEFAULT_HTTP_PORT); hConnectHandle = InternetConnectW(internet, (WCHAR*) server.utf16(), port, 0, 0, INTERNET_SERVICE_HTTP, 0, 0); if (hConnectHandle == 0) { QString errMsg; WPMUtils::formatMessage(GetLastError(), &errMsg); job->setErrorMessage(errMsg); } } // flags: http://msdn.microsoft.com/en-us/library/aa383661(v=vs.85).aspx // We support accepting any mime file type since this is a simple download // of a file HINTERNET hResourceHandle = 0; if (job->shouldProceed()) { LPCTSTR ppszAcceptTypes[2]; ppszAcceptTypes[0] = L"*/*"; ppszAcceptTypes[1] = NULL; DWORD flags = (url.scheme() == "https" ? INTERNET_FLAG_SECURE : 0); if (keepConnection) flags |= INTERNET_FLAG_KEEP_CONNECTION; flags |= INTERNET_FLAG_RESYNCHRONIZE; if (!useCache) flags |= INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD; hResourceHandle = HttpOpenRequestW(hConnectHandle, reinterpret_cast<LPCWSTR>(verb.utf16()), (WCHAR*) resource.utf16(), 0, 0, ppszAcceptTypes, flags, 0); if (hResourceHandle == 0) { QString errMsg; WPMUtils::formatMessage(GetLastError(), &errMsg); job->setErrorMessage(errMsg); } } if (job->shouldProceed()) { job->checkOSCall(HttpAddRequestHeadersW(hResourceHandle, L"Accept-Encoding: gzip, deflate", -1, HTTP_ADDREQ_FLAG_ADD)); } DWORD dwStatus, dwStatusSize = sizeof(dwStatus); // qDebug() << "download.5"; int callNumber = 0; while (job->shouldProceed()) { // qDebug() << "download.5.1"; DWORD sendRequestError = 0; if (!HttpSendRequestW(hResourceHandle, reinterpret_cast<LPCWSTR>(request.headers.utf16()), -1, const_cast<char*>(request.postData.data()), request.postData.length())) { sendRequestError = GetLastError(); } // http://msdn.microsoft.com/en-us/library/aa384220(v=vs.85).aspx if (!HttpQueryInfo(hResourceHandle, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE, &dwStatus, &dwStatusSize, NULL)) { QString errMsg; WPMUtils::formatMessage(GetLastError(), &errMsg); job->setErrorMessage(errMsg); break; } /* qDebug() << callNumber << sendRequestError << dwStatus << request.httpMethod << request.url.toString(); */ // 2XX if (sendRequestError == 0) { DWORD hundreds = dwStatus / 100; if (hundreds == 2 || hundreds == 5) break; } // the InternetErrorDlg calls below can either handle // sendRequestError <> 0 or HTTP error code <> 2xx void* p = 0; // both calls to InternetErrorDlg should be enclosed by one // mutex, so that only one dialog will be shown loginDialogMutex.lock(); DWORD r; if (callNumber == 0) { r = InternetErrorDlg(0, hResourceHandle, sendRequestError, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA | FLAGS_ERROR_UI_FLAGS_NO_UI, &p); if (r == ERROR_SUCCESS && interactive) r = ERROR_INTERNET_FORCE_RETRY; } else if (interactive) { if (parentWindow) { r = InternetErrorDlg(parentWindow, hResourceHandle, sendRequestError, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, &p); } else { QString e = inputPassword(hConnectHandle, dwStatus); //qDebug() << "inputPassword: "******"HTTP status code %1")).arg(dwStatus)); } } else if (r == ERROR_INTERNET_FORCE_RETRY) { // nothing } else if (r == ERROR_CANCELLED) { job->setErrorMessage(QObject::tr("Cancelled by the user")); } else if (r == ERROR_INVALID_HANDLE) { job->setErrorMessage(QObject::tr("Invalid handle")); } else { job->setErrorMessage(QString( QObject::tr("Unknown error %1 from InternetErrorDlg")).arg(r)); } loginDialogMutex.unlock(); if (!job->shouldProceed()) break; // read all the data before re-sending the request char smallBuffer[4 * 1024]; while (true) { DWORD read; if (!InternetReadFile(hResourceHandle, &smallBuffer, sizeof(smallBuffer), &read)) { QString errMsg; WPMUtils::formatMessage(GetLastError(), &errMsg); job->setErrorMessage(errMsg); goto out; } // qDebug() << "read some bytes " << read; if (read == 0) break; } callNumber++; }; // while (job->shouldProceed()) out: if (job->shouldProceed()) { // http://msdn.microsoft.com/en-us/library/aa384220(v=vs.85).aspx if (!HttpQueryInfo(hResourceHandle, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE, &dwStatus, &dwStatusSize, NULL)) { QString errMsg; WPMUtils::formatMessage(GetLastError(), &errMsg); job->setErrorMessage(errMsg); } else { // 2XX if (dwStatus / 100 != 2) { job->setErrorMessage(QString( QObject::tr("HTTP status code %1")).arg(dwStatus)); } } } if (job->shouldProceed()) { job->setProgress(0.03); job->setTitle(initialTitle + " / " + QObject::tr("Downloading")); } // MIME type if (job->shouldProceed()) { if (mime) { WCHAR mimeBuffer[1024]; DWORD bufferLength = sizeof(mimeBuffer); DWORD index = 0; if (!HttpQueryInfoW(hResourceHandle, HTTP_QUERY_CONTENT_TYPE, &mimeBuffer, &bufferLength, &index)) { QString errMsg; WPMUtils::formatMessage(GetLastError(), &errMsg); job->setErrorMessage(errMsg); } else { mime->setUtf16((ushort*) mimeBuffer, bufferLength / 2); } } } bool gzip = false; // Content-Encoding if (job->shouldProceed()) { WCHAR contentEncodingBuffer[1024]; DWORD bufferLength = sizeof(contentEncodingBuffer); DWORD index = 0; if (HttpQueryInfoW(hResourceHandle, HTTP_QUERY_CONTENT_ENCODING, &contentEncodingBuffer, &bufferLength, &index)) { QString contentEncoding; contentEncoding.setUtf16((ushort*) contentEncodingBuffer, bufferLength / 2); gzip = contentEncoding == "gzip" || contentEncoding == "deflate"; } job->setProgress(0.04); } // Content-Disposition if (job->shouldProceed()) { if (contentDisposition) { WCHAR cdBuffer[1024]; wcscpy(cdBuffer, L"Content-Disposition"); DWORD bufferLength = sizeof(cdBuffer); DWORD index = 0; if (HttpQueryInfoW(hResourceHandle, HTTP_QUERY_CUSTOM, &cdBuffer, &bufferLength, &index)) { contentDisposition->setUtf16((ushort*) cdBuffer, bufferLength / 2); } } } int64_t contentLength = -1; // content length if (job->shouldProceed()) { WCHAR contentLengthBuffer[100]; DWORD bufferLength = sizeof(contentLengthBuffer); DWORD index = 0; if (HttpQueryInfoW(hResourceHandle, HTTP_QUERY_CONTENT_LENGTH, contentLengthBuffer, &bufferLength, &index)) { QString s; s.setUtf16((ushort*) contentLengthBuffer, bufferLength / 2); bool ok; contentLength = s.toLongLong(&ok, 10); if (!ok) contentLength = 0; } job->setProgress(0.05); } if (job->shouldProceed()) { Job* sub = job->newSubJob(0.95, QObject::tr("Reading the data")); readData(sub, hResourceHandle, file, sha1, gzip, contentLength, alg); if (!sub->getErrorMessage().isEmpty()) job->setErrorMessage(sub->getErrorMessage()); } if (hResourceHandle) InternetCloseHandle(hResourceHandle); if (hConnectHandle) InternetCloseHandle(hConnectHandle); if (internet) InternetCloseHandle(internet); if (job->shouldProceed()) job->setProgress(1); job->setTitle(initialTitle); job->complete(); return contentLength; }
{ Q_UNUSED(data) // Not included in V2 signatures. Q_D(const AwsSignatureV2); // Set the AccessKeyId, SignatureMethod, SignatureVersion and Timestamp query items, if not already. d->adornRequest(request, credentials); // Calculate the signature. const QByteArray stringToSign = d->canonicalRequest(operation, request.url()); const QString signature = QString::fromUtf8(QUrl::toPercentEncoding(QString::fromUtf8( QMessageAuthenticationCode::hash(stringToSign, credentials.secretKey().toUtf8(), d->hashAlgorithm).toBase64()))); // Append the signature to the request. QUrl url = request.url(); url.setQuery(url.query() + QLatin1String("&Signature=") + signature); request.setUrl(url); } int AwsSignatureV2::version() const { return 2; } /** * @internal * * @class AwsSignatureV2Private * * @brief Private implementation for AwsSignatureV2. *
bool HTTPManager::handleHTTPRequest(HTTPConnection* connection, const QUrl& url, bool skipSubHandler) { // Reject paths with embedded NULs if (url.path().contains(QChar(0x00))) { connection->respond(HTTPConnection::StatusCode400, "Embedded NULs not allowed in requests"); qCWarning(embeddedwebserver) << "Received a request with embedded NULs"; return true; } if (!skipSubHandler && requestHandledByRequestHandler(connection, url)) { // this request was handled by our request handler object // so we don't need to attempt to do so in the document root return true; } if (!_documentRoot.isEmpty()) { // check to see if there is a file to serve from the document root for this path QString subPath = url.path(); // remove any slash at the beginning of the path if (subPath.startsWith('/')) { subPath.remove(0, 1); } QString absoluteDocumentRoot { QFileInfo(_documentRoot).absolutePath() }; QString filePath; QFileInfo pathFileInfo { _documentRoot + subPath }; QString absoluteFilePath { pathFileInfo.absoluteFilePath() }; // The absolute path for this file isn't under the document root if (absoluteFilePath.indexOf(absoluteDocumentRoot) != 0) { qCWarning(embeddedwebserver) << absoluteFilePath << "is outside the document root"; connection->respond(HTTPConnection::StatusCode400, "Requested path outside document root"); return true; } if (pathFileInfo.isFile()) { filePath = absoluteFilePath; } else if (subPath.size() > 0 && !subPath.endsWith('/') && pathFileInfo.isDir()) { // this could be a directory with a trailing slash // send a redirect to the path with a slash so we can QString redirectLocation = '/' + subPath + '/'; if (!url.query().isEmpty()) { redirectLocation += "?" + url.query(); } QHash<QByteArray, QByteArray> redirectHeader; redirectHeader.insert(QByteArray("Location"), redirectLocation.toUtf8()); connection->respond(HTTPConnection::StatusCode302, "", HTTPConnection::DefaultContentType, redirectHeader); return true; } // if the last thing is a trailing slash then we want to look for index file if (subPath.endsWith('/') || subPath.size() == 0) { QStringList possibleIndexFiles = QStringList() << "index.html" << "index.shtml"; foreach (const QString& possibleIndexFilename, possibleIndexFiles) { if (QFileInfo(absoluteFilePath + possibleIndexFilename).exists()) { filePath = absoluteFilePath + possibleIndexFilename; break; } } }
void Ssu::sendRegistration(QString usernameDomain, QString password){ errorFlag = false; QString ssuCaCertificate, ssuRegisterUrl; QString username, domainName; SsuLog *ssuLog = SsuLog::instance(); SsuCoreConfig *settings = SsuCoreConfig::instance(); SsuDeviceInfo deviceInfo; QNetworkRequest request; request.setAttribute(SSU_NETWORK_REQUEST_DOMAIN_DATA, domain()); ssuLog->print(LOG_DEBUG, QString("Saving current domain before request: '%1'").arg(domain())); // Username can include also domain, (user@domain), separate those if (usernameDomain.contains('@')) { // separate domain/username and set domain username = usernameDomain.section('@', 0, 0); domainName = usernameDomain.section('@', 1, 1); setDomain(domainName); } else { // No domain defined username = usernameDomain; if (settings->contains("default-rnd-domain")) setDomain(settings->value("default-rnd-domain").toString()); } ssuCaCertificate = SsuRepoManager::caCertificatePath(); if (ssuCaCertificate.isEmpty()){ setError("CA certificate for SSU not set ('_ca-certificate in domain')"); return; } if (!settings->contains("register-url")){ ssuRegisterUrl = repoUrl("register-url"); if (ssuRegisterUrl.isEmpty()){ setError("URL for SSU registration not set (config key 'register-url')"); return; } } else ssuRegisterUrl = settings->value("register-url").toString(); QString IMEI = deviceInfo.deviceUid(); if (IMEI == ""){ setError("No valid UID available for your device. For phones: is your modem online?"); return; } QSslConfiguration sslConfiguration; if (!useSslVerify()) sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone); sslConfiguration.setCaCertificates(QSslCertificate::fromPath(ssuCaCertificate)); request.setUrl(QUrl(QString(ssuRegisterUrl) .arg(IMEI) )); request.setSslConfiguration(sslConfiguration); request.setRawHeader("Authorization", "Basic " + QByteArray(QString("%1:%2") .arg(username).arg(password) .toLatin1()).toBase64()); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QUrl form; #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QUrlQuery q; q.addQueryItem("protocolVersion", SSU_PROTOCOL_VERSION); q.addQueryItem("deviceModel", deviceInfo.deviceModel()); if (!domain().isEmpty()){ q.addQueryItem("domain", domain()); } form.setQuery(q); #else form.addQueryItem("protocolVersion", SSU_PROTOCOL_VERSION); form.addQueryItem("deviceModel", deviceInfo.deviceModel()); if (!domain().isEmpty()){ form.addQueryItem("domain", domain()); } #endif ssuLog->print(LOG_DEBUG, QString("Sending request to %1") .arg(request.url().url())); QNetworkReply *reply; pendingRequests++; #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) reply = manager->post(request, form.query(QUrl::FullyEncoded).toStdString().c_str()); #else reply = manager->post(request, form.encodedQuery()); #endif // we could expose downloadProgress() from reply in case we want progress info QString homeUrl = settings->value("home-url").toString().arg(username); if (!homeUrl.isEmpty()){ // clear header, the other request bits are reusable request.setHeader(QNetworkRequest::ContentTypeHeader, 0); request.setUrl(homeUrl + "/authorized_keys"); ssuLog->print(LOG_DEBUG, QString("Trying to get SSH keys from %1").arg(request.url().toString())); pendingRequests++; manager->get(request); } }
void UPnpCDSVideo::PopulateArtworkURIS(CDSObject* pItem, int nVidID, const QUrl& URIBase) { QUrl artURI = URIBase; artURI.setPath("/Content/GetVideoArtwork"); QUrlQuery artQuery; artQuery.addQueryItem("Id", QString::number(nVidID)); artURI.setQuery(artQuery); // Prefer JPEG over PNG here, although PNG is allowed JPEG probably // has wider device support and crucially the filesizes are smaller // which speeds up loading times over the network // We MUST include the thumbnail size, but since some clients may use the // first image they see and the thumbnail is tiny, instead return the // medium first. The large could be very large, which is no good if the // client is pulling images for an entire list at once! // Thumbnail // At least one albumArtURI must be a ThumbNail (TN) no larger // than 160x160, and it must also be a jpeg QUrl thumbURI = artURI; QUrlQuery thumbQuery(thumbURI.query()); if (pItem->m_sClass == "object.item.videoItem") // Show screenshot for TV, coverart for movies thumbQuery.addQueryItem("Type", "screenshot"); else thumbQuery.addQueryItem("Type", "coverart"); thumbQuery.addQueryItem("Width", "160"); thumbQuery.addQueryItem("Height", "160"); thumbURI.setQuery(thumbQuery); // Small // Must be no more than 640x480 QUrl smallURI = artURI; QUrlQuery smallQuery(smallURI.query()); smallQuery.addQueryItem("Type", "coverart"); smallQuery.addQueryItem("Width", "640"); smallQuery.addQueryItem("Height", "480"); smallURI.setQuery(smallQuery); // Medium // Must be no more than 1024x768 QUrl mediumURI = artURI; QUrlQuery mediumQuery(mediumURI.query()); mediumQuery.addQueryItem("Type", "coverart"); mediumQuery.addQueryItem("Width", "1024"); mediumQuery.addQueryItem("Height", "768"); mediumURI.setQuery(mediumQuery); // Large // Must be no more than 4096x4096 - for our purposes, just return // a fullsize image QUrl largeURI = artURI; QUrlQuery largeQuery(largeURI.query()); largeQuery.addQueryItem("Type", "fanart"); largeURI.setQuery(largeQuery); QList<Property*> propList = pItem->GetProperties("albumArtURI"); if (propList.size() >= 4) { Property *pProp = propList.at(0); if (pProp) { pProp->SetValue(mediumURI.toEncoded()); pProp->AddAttribute("dlna:profileID", "JPEG_MED"); pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0"); } pProp = propList.at(1); if (pProp) { pProp->SetValue(thumbURI.toEncoded()); pProp->AddAttribute("dlna:profileID", "JPEG_TN"); pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0"); } pProp = propList.at(2); if (pProp) { pProp->SetValue(smallURI.toEncoded()); pProp->AddAttribute("dlna:profileID", "JPEG_SM"); pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0"); } pProp = propList.at(3); if (pProp) { pProp->SetValue(largeURI.toEncoded()); pProp->AddAttribute("dlna:profileID", "JPEG_LRG"); pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0"); } } if (pItem->m_sClass.startsWith("object.item.videoItem")) { QString sProtocol; sProtocol = DLNA::ProtocolInfoString(UPNPProtocol::kHTTP, "image/jpeg", QSize(1024, 768)); pItem->AddResource( sProtocol, mediumURI.toEncoded()); sProtocol = DLNA::ProtocolInfoString(UPNPProtocol::kHTTP, "image/jpeg", QSize(160, 160)); pItem->AddResource( sProtocol, thumbURI.toEncoded()); sProtocol = DLNA::ProtocolInfoString(UPNPProtocol::kHTTP, "image/jpeg", QSize(640, 480)); pItem->AddResource( sProtocol, smallURI.toEncoded()); sProtocol = DLNA::ProtocolInfoString(UPNPProtocol::kHTTP, "image/jpeg", QSize(1920, 1080)); // Not the actual res, we don't know that pItem->AddResource( sProtocol, largeURI.toEncoded()); } }
void HttpProxy::onSocketReadyRead() { QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender()); QTcpSocket *proxySocket = nullptr; QByteArray reqData = socket->readAll(); int pos = reqData.indexOf("\r\n"); QByteArray reqLine = reqData.left(pos); reqData.remove(0, pos + 2); QList<QByteArray> entries = reqLine.split(' '); QByteArray method = entries.value(0); QByteArray address = entries.value(1); QByteArray version = entries.value(2); QString host; quint16 port; QString key; if (method != "CONNECT") { QUrl url = QUrl::fromEncoded(address); if (!url.isValid()) { emit info("Invalid URL: " + url.toString()); socket->disconnectFromHost(); return; } host = url.host(); port = url.port(80); QString req = url.path(); if (url.hasQuery()) { req.append('?').append(url.query()); } reqLine = method + " " + req.toUtf8() + " " + version + "\r\n"; reqData.prepend(reqLine); key = host + ':' + QString::number(port); proxySocket = socket->findChild<QTcpSocket *>(key); if (proxySocket) { proxySocket->write(reqData); return;//if we find an existing socket, then use it and return } } else {//CONNECT method /* * according to http://tools.ietf.org/html/draft-luotonen-ssl-tunneling-03 * the first line would CONNECT HOST:PORT VERSION */ QList<QByteArray> host_port_list = address.split(':'); host = QString(host_port_list.first()); port = host_port_list.last().toUShort(); } proxySocket = new QTcpSocket(socket); proxySocket->setProxy(upstreamProxy); if (method != "CONNECT") { proxySocket->setObjectName(key); proxySocket->setProperty("reqData", reqData); connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnected); connect (proxySocket, &QTcpSocket::readyRead, this, &HttpProxy::onProxySocketReadyRead); } else { connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnectedHttps); } connect (proxySocket, &QTcpSocket::disconnected, proxySocket, &QTcpSocket::deleteLater); connect (proxySocket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error), this, &HttpProxy::onSocketError); proxySocket->connectToHost(host, port); }
void VHttpProxy::run(VTcpSession* tcpSession) { LOG_DEBUG("stt"); // gilgil temp 2013.10.19 VTcpSession* inSession = tcpSession; VHttpRequest request; VTcpClient outClient; VHttpProxyOutInThread* thread = NULL; QByteArray totalPacket; while (true) { QByteArray packet; int readLen = inSession->read(packet); if (readLen == VERR_FAIL) break; // LOG_DEBUG("%s", packet.data()); // gilgil temp totalPacket += packet; if (!request.parse(totalPacket)) { if (outClient.active()) { outClient.tcpSession->write(totalPacket); totalPacket = ""; } continue; } QString host; int port; QUrl url = request.requestLine.path; if (!url.isRelative()) { host = url.host(); port = url.port(); if (port == -1) port = 80; QByteArray newPath = url.path().toUtf8(); if (url.hasQuery()) newPath += "?" + url.query(QUrl::FullyEncoded).toLatin1(); request.requestLine.path = newPath; } else if (!request.findHost(host, port)) { LOG_ERROR("can not find host:%s", totalPacket.data()); break; } if (outClient.host != host || outClient.port != port) { outClient.close(); if (thread != NULL) delete thread; outClient.host = host; outClient.port = port; if (!outClient.open()) { LOG_ERROR("%s", outClient.error.msg); break; } thread = new VHttpProxyOutInThread(&outClient, inSession, this); thread->open(); } emit beforeRequest(request, inSession, &outClient); outClient.tcpSession->write(request.toByteArray()); totalPacket = ""; } LOG_DEBUG("end"); // gilgil temp 2013.10.19 outClient.close(); if (thread != NULL) delete thread; }
/*! \internal */ void QWebSocketPrivate::open(const QUrl &url, bool mask) { //just delete the old socket for the moment; //later, we can add more 'intelligent' handling by looking at the URL //m_pSocket.reset(); Q_Q(QWebSocket); if (!url.isValid() || url.toString().contains(QStringLiteral("\r\n"))) { setErrorString(QWebSocket::tr("Invalid URL.")); Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError); return; } QTcpSocket *pTcpSocket = m_pSocket.take(); if (pTcpSocket) { releaseConnections(pTcpSocket); pTcpSocket->deleteLater(); } //if (m_url != url) if (Q_LIKELY(!m_pSocket)) { m_dataProcessor.clear(); m_isClosingHandshakeReceived = false; m_isClosingHandshakeSent = false; setRequestUrl(url); QString resourceName = url.path(); if (resourceName.contains(QStringLiteral("\r\n"))) { setRequestUrl(QUrl()); //clear requestUrl setErrorString(QWebSocket::tr("Invalid resource name.")); Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError); return; } if (!url.query().isEmpty()) { if (!resourceName.endsWith(QChar::fromLatin1('?'))) { resourceName.append(QChar::fromLatin1('?')); } resourceName.append(url.query()); } if (resourceName.isEmpty()) resourceName = QStringLiteral("/"); setResourceName(resourceName); enableMasking(mask); #ifndef QT_NO_SSL if (url.scheme() == QStringLiteral("wss")) { if (!QSslSocket::supportsSsl()) { const QString message = QWebSocket::tr("SSL Sockets are not supported on this platform."); setErrorString(message); Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError); } else { QSslSocket *sslSocket = new QSslSocket; m_pSocket.reset(sslSocket); if (Q_LIKELY(m_pSocket)) { m_pSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1); m_pSocket->setReadBufferSize(m_readBufferSize); m_pSocket->setPauseMode(m_pauseMode); makeConnections(m_pSocket.data()); QObject::connect(sslSocket, &QSslSocket::encryptedBytesWritten, q, &QWebSocket::bytesWritten); typedef void (QSslSocket:: *sslErrorSignalType)(const QList<QSslError> &); QObject::connect(sslSocket, static_cast<sslErrorSignalType>(&QSslSocket::sslErrors), q, &QWebSocket::sslErrors); setSocketState(QAbstractSocket::ConnectingState); sslSocket->setSslConfiguration(m_configuration.m_sslConfiguration); if (Q_UNLIKELY(m_configuration.m_ignoreSslErrors)) sslSocket->ignoreSslErrors(); else sslSocket->ignoreSslErrors(m_configuration.m_ignoredSslErrors); #ifndef QT_NO_NETWORKPROXY sslSocket->setProxy(m_configuration.m_proxy); #endif sslSocket->connectToHostEncrypted(url.host(), url.port(443)); } else { const QString message = QWebSocket::tr("Out of memory."); setErrorString(message); Q_EMIT q->error(QAbstractSocket::SocketResourceError); } } } else #endif if (url.scheme() == QStringLiteral("ws")) { m_pSocket.reset(new QTcpSocket); if (Q_LIKELY(m_pSocket)) { m_pSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1); m_pSocket->setReadBufferSize(m_readBufferSize); m_pSocket->setPauseMode(m_pauseMode); makeConnections(m_pSocket.data()); QObject::connect(m_pSocket.data(), &QAbstractSocket::bytesWritten, q, &QWebSocket::bytesWritten); setSocketState(QAbstractSocket::ConnectingState); #ifndef QT_NO_NETWORKPROXY m_pSocket->setProxy(m_configuration.m_proxy); #endif m_pSocket->connectToHost(url.host(), url.port(80)); } else { const QString message = QWebSocket::tr("Out of memory."); setErrorString(message); Q_EMIT q->error(QAbstractSocket::SocketResourceError); } } else { const QString message = QWebSocket::tr("Unsupported WebSocket scheme: %1").arg(url.scheme()); setErrorString(message); Q_EMIT q->error(QAbstractSocket::UnsupportedSocketOperationError); } } }
void MANProtocol::get(const QUrl& url ) { qCDebug(KIO_MAN_LOG) << "GET " << url.url(); QString title, section; if (!parseUrl(url.path(), title, section)) { showMainIndex(); return; } // tell the mimetype mimeType("text/html"); // see if an index was requested if (url.query().isEmpty() && (title.isEmpty() || title == "/" || title == ".")) { if (section == "index" || section.isEmpty()) showMainIndex(); else showIndex(section); return; } const QStringList foundPages=findPages(section, title); bool pageFound=true; if (foundPages.isEmpty()) { outputError(i18n("No man page matching to %1 found.<br /><br />" "Check that you have not mistyped the name of the page that you want.<br />" "Check that you have typed the name using the correct upper and lower case characters.<br />" "If everything looks correct, then you may need to improve the search path " "for man pages; either using the environment variable MANPATH or using a matching file " "in the /etc directory.", title.toHtmlEscaped())); pageFound=false; } else if (foundPages.count()>1) { pageFound=false; //check for the case that there is foo.1 and foo.1.gz found: // ### TODO make it more generic (other extensions) if ((foundPages.count()==2) && ((QString(foundPages[0]+".gz") == foundPages[1]) || (foundPages[0] == QString(foundPages[1]+".gz")))) pageFound=true; else outputMatchingPages(foundPages); } //yes, we found exactly one man page if (pageFound) { setResourcePath(m_cssPath); setCssFile(m_manCSSFile); m_outputBuffer.open(QIODevice::WriteOnly); const QByteArray filename=QFile::encodeName(foundPages[0]); char *buf = readManPage(filename); if (!buf) { outputError(i18n("Open of %1 failed.", title)); finished(); return; } // will call output_real scan_man_page(buf); delete [] buf; output(0); // flush m_outputBuffer.close(); data(m_outputBuffer.buffer()); m_outputBuffer.setData(QByteArray()); // tell we are done data(QByteArray()); } finished(); }