QMLManager::QMLManager() : m_locationServiceEnabled(false), m_verboseEnabled(false), reply(0), deletedDive(0), deletedTrip(0), m_updateSelectedDive(-1), m_selectedDiveTimestamp(0), m_credentialStatus(UNKNOWN), m_lastDevicePixelRatio(1.0), alreadySaving(false) { m_instance = this; connect(qobject_cast<QApplication *>(QApplication::instance()), &QApplication::applicationStateChanged, this, &QMLManager::applicationStateChanged); appendTextToLog(getUserAgent()); appendTextToLog(QStringLiteral("build with Qt Version %1, runtime from Qt Version %2").arg(QT_VERSION_STR).arg(qVersion())); qDebug() << "Starting" << getUserAgent(); qDebug() << QStringLiteral("build with Qt Version %1, runtime from Qt Version %2").arg(QT_VERSION_STR).arg(qVersion()); setStartPageText(tr("Starting...")); setAccessingCloud(-1); setShowPin(false); // create location manager service locationProvider = new GpsLocation(&appendTextToLogStandalone, this); connect(locationProvider, SIGNAL(haveSourceChanged()), this, SLOT(hasLocationSourceChanged())); setLocationServiceAvailable(locationProvider->hasLocationsSource()); set_git_update_cb(&gitProgressCB); // make sure we know if the current cloud repo has been successfully synced syncLoadFromCloud(); }
bool checkNewVersion(const Uuid& uuid, const std::string& extraParams, CheckUpdateDelegate* delegate) { #ifndef UPDATE_URL #define UPDATE_URL "" #pragma message("warning: Define UPDATE_URL macro") #endif std::string url = UPDATE_URL; if (!uuid.empty()) { url += "&uuid="; url += uuid; } if (!extraParams.empty()) { url += "&"; url += extraParams; } m_request.reset(new net::HttpRequest(url)); net::HttpHeaders headers; headers.setHeader("User-Agent", getUserAgent()); m_request->setHeaders(headers); std::stringstream body; net::HttpResponse response(&body); if (m_request->send(response)) { TRACE("Checking updates: %s (User-Agent: %s)\n", url.c_str(), getUserAgent().c_str()); TRACE("Response:\n--\n%s--\n", body.str().c_str()); CheckUpdateResponse data(body.str()); delegate->onResponse(data); return true; } else return false; }
QString SystemComponent::debugInformation() { QString debugInfo; QTextStream stream(&debugInfo); stream << "Plex Media Player" << endl; stream << " Version: " << Version::GetVersionString() << " built: " << Version::GetBuildDate() << endl; stream << " Web Client Version: " << Version::GetWebVersion() << endl; stream << " Platform: " << getPlatformTypeString() << "-" << getPlatformArchString() << endl; stream << " User-Agent: " << getUserAgent() << endl; stream << " Qt version: " << qVersion() << endl; stream << endl; stream << "Files" << endl; stream << " Log file: " << Paths::logDir(Names::MainName() + ".log") << endl; stream << " Config file: " << Paths::dataDir(Names::MainName() + ".conf") << endl; stream << endl; #ifdef Q_OS_UNIX stream << "Network" << endl; QMap<QString, QString> networks = networkInterfaces(); foreach(const QString& net, networks.keys()) stream << " " << net << ": " << networks[net] << endl; #endif stream << flush; return debugInfo; }
QString SystemComponent::debugInformation() { QString debugInfo; QTextStream stream(&debugInfo); stream << "Plex Media Player" << endl; stream << " Version: " << Version::GetVersionString() << " built: " << Version::GetBuildDate() << endl; stream << " Web Client Version: " << Version::GetWebVersion() << endl; stream << " Web Client URL: " << SettingsComponent::Get().value(SETTINGS_SECTION_PATH, "startupurl").toString() << endl; stream << " Platform: " << getPlatformTypeString() << "-" << getPlatformArchString() << endl; stream << " User-Agent: " << getUserAgent() << endl; stream << " Qt version: " << qVersion() << endl; stream << endl; stream << "Files" << endl; stream << " Log file: " << Paths::logDir(Names::MainName() + ".log") << endl; stream << " Config file: " << Paths::dataDir(Names::MainName() + ".conf") << endl; stream << endl; stream << "Network Addresses" << endl; foreach (const QString& addr, networkAddresses()) { stream << " " << addr << endl; } stream << endl; stream << flush; return debugInfo; }
QString QtWebKitWebBackend::getUserAgent(const QString &pattern) const { if (!pattern.isEmpty()) { if (m_userAgents.contains(pattern)) { return (m_userAgents[pattern].isEmpty() ? pattern : m_userAgents[pattern]); } QString userAgent = pattern; QMap<QString, QString>::iterator iterator; for (iterator = m_userAgentComponents.begin(); iterator != m_userAgentComponents.end(); ++iterator) { userAgent = userAgent.replace(QStringLiteral("{%1}").arg(iterator.key()), iterator.value()); } m_userAgents[pattern] = ((pattern == userAgent) ? QString() : userAgent); return userAgent; } const UserAgentInformation userAgent = NetworkManagerFactory::getUserAgent(SettingsManager::getValue(QLatin1String("Network/UserAgent")).toString()); return ((userAgent.value.isEmpty()) ? QString() : getUserAgent(userAgent.value)); }
void DiveShareExportDialog::doUpload() { //Store current settings QSettings settings; settings.setValue("diveshareExport/uid", ui->txtUID->text()); settings.setValue("diveshareExport/private", ui->chkPrivate->isChecked()); //Change UI into results mode ui->frameConfigure->setVisible(false); ui->frameResults->setVisible(true); ui->progressBar->setVisible(true); ui->progressBar->setRange(0, 0); //generate json struct membuffer buf = { 0 }; export_list(&buf, NULL, exportSelected, false); QByteArray json_data(buf.buffer, buf.len); free_buffer(&buf); //Request to server QNetworkRequest request; if (ui->chkPrivate->isChecked()) request.setUrl(QUrl(DIVESHARE_BASE_URI "/upload?private=true")); else request.setUrl(QUrl(DIVESHARE_BASE_URI "/upload")); request.setRawHeader("User-Agent", getUserAgent().toUtf8()); if (ui->txtUID->text().length() != 0) request.setRawHeader("X-UID", ui->txtUID->text().toUtf8()); reply = WebServices::manager()->put(request, json_data); QObject::connect(reply, SIGNAL(finished()), this, SLOT(finishedSlot())); }
void ReverseGeoLookupThread::run() { if (geo_lookup_data.isEmpty()) return; QNetworkRequest request; QNetworkAccessManager *rgl = new QNetworkAccessManager(); request.setRawHeader("Accept", "text/json"); request.setRawHeader("User-Agent", getUserAgent().toUtf8()); QEventLoop loop; QString apiCall("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=%1&lat=%2&lon=%3"); Q_FOREACH (const GeoLookupInfo& info, geo_lookup_data ) { request.setUrl(apiCall.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0)); QNetworkReply *reply = rgl->get(request); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QJsonParseError errorObject; QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &errorObject); if (errorObject.error != QJsonParseError::NoError) { qDebug() << errorObject.errorString(); } else { QJsonObject obj = jsonDoc.object(); QJsonObject address = obj.value("address").toObject(); qDebug() << "found country:" << address.value("country").toString(); struct dive_site *ds = get_dive_site_by_uuid(info.uuid); ds->notes = add_to_string(ds->notes, "countrytag: %s", address.value("country").toString().toUtf8().data()); } reply->deleteLater(); }
void WebCoreClass::setWCCookies(HttpHandle& hh) { std::lock_guard<std::mutex> l(m_mSessLock); hh->addCookie("freeman", m_szIdCookie.c_str()); hh->addCookie("masterchief", gcString(m_szSessCookie).c_str()); hh->setUserAgent(getUserAgent()); }
QString QMLManager::getVersion() const { QRegExp versionRe(".*:([()\\.,\\d]+).*"); if (!versionRe.exactMatch(getUserAgent())) return QString(); return versionRe.cap(1); }
void WebCoreClass::setMCFCookies(MCFCore::Misc::UserCookies* uc) { std::lock_guard<std::mutex> l(m_mSessLock); uc->setUserId(m_uiUserId); uc->setId(m_szIdCookie.c_str()); uc->setSess(gcString(m_szSessCookie).c_str()); uc->setUAgent(getUserAgent()); }
QMLManager::QMLManager() : m_locationServiceEnabled(false), m_verboseEnabled(false), m_credentialStatus(UNKNOWN), reply(0) { m_instance = this; appendTextToLog(getUserAgent()); appendTextToLog(QStringLiteral("build with Qt Version %1, runtime from Qt Version %2").arg(QT_VERSION_STR).arg(qVersion())); qDebug() << "Starting" << getUserAgent(); qDebug() << QStringLiteral("build with Qt Version %1, runtime from Qt Version %2").arg(QT_VERSION_STR).arg(qVersion()); setStartPageText(tr("Starting...")); // create location manager service locationProvider = new GpsLocation(&appendTextToLogStandalone, this); set_git_update_cb(&gitProgressCB); // make sure we know if the current cloud repo has been successfully synced syncLoadFromCloud(); }
// Function: send_headers // Send HTTP headers sends all the HTTP headers down the stream. void send_headers(std::ostream& stream) const { stream << "Host: " << getHost() << "\r\n" << "User-Agent: " << getUserAgent() << "\r\n" << "Connection: close\r\n"; if(this->accept != "") { stream << getAccept(); } }
bool CheckCloudConnection::checkServer() { if (verbose) fprintf(stderr, "Checking cloud connection...\n"); QTimer timer; timer.setSingleShot(true); QEventLoop loop; QNetworkRequest request; request.setRawHeader("Accept", "text/plain"); request.setRawHeader("User-Agent", getUserAgent().toUtf8()); request.setRawHeader("Client-Id", getUUID().toUtf8()); request.setUrl(QString(prefs.cloud_base_url) + TEAPOT); QNetworkAccessManager *mgr = new QNetworkAccessManager(); reply = mgr->get(request); connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); connect(reply, &QNetworkReply::sslErrors, this, &CheckCloudConnection::sslErrors); for (int seconds = 1; seconds <= prefs.cloud_timeout; seconds++) { timer.start(1000); // wait the given number of seconds (default 5) loop.exec(); if (timer.isActive()) { // didn't time out, did we get the right response? timer.stop(); if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == HTTP_I_AM_A_TEAPOT && reply->readAll() == QByteArray(MILK)) { reply->deleteLater(); mgr->deleteLater(); if (verbose > 1) qWarning() << "Cloud storage: successfully checked connection to cloud server"; git_storage_update_progress(false, "successfully checked cloud connection"); return true; } } else if (seconds < prefs.cloud_timeout) { QString text = QString("waited %1 sec for cloud connetion").arg(seconds); git_storage_update_progress(false, qPrintable(text)); } else { disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit())); reply->abort(); } } git_storage_update_progress(false, "cloud connection failed"); prefs.git_local_only = true; if (verbose) qDebug() << "connection test to cloud server failed" << reply->error() << reply->errorString() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << reply->readAll(); reply->deleteLater(); mgr->deleteLater(); if (verbose) qWarning() << "Cloud storage: unable to connect to cloud server"; return false; }
void WebCoreClass::downloadImage(WebCore::Misc::DownloadImageInfo *dii, volatile bool &stop) { if (!dii) throw gcException(ERR_BADITEM); const char* imageUrl = dii->url.c_str(); uint32 hash = UTIL::MISC::RSHash_CSTR(imageUrl); std::string szPath = m_ImageCache.getImagePath(hash); if (UTIL::FS::isValidFile(szPath)) { dii->outPath = szPath; return; } if (strncmp(imageUrl,"http://", 7) != 0) throw gcException(ERR_INVALIDDATA, gcString("The url {0} is not a valid http url", imageUrl)); gcString appDataPath = UTIL::OS::getCachePath(L"images"); gcString fileName = UTIL::FS::Path(imageUrl, "", true).getFile().getFile(); if (dii->id.isOk()) fileName = gcString("{0}_{1}", dii->id.toInt64(), fileName); else fileName = gcString("{0}_{1}", hash, fileName); HttpHandle hh(imageUrl); hh->setUserAgent(getUserAgent()); hh->getProgressEvent() += extraDelegate<WebCoreClass, Prog_s, volatile bool&>(this, &WebCoreClass::onHttpProg, stop); hh->getWeb(); if (hh->getDataSize() == 0) throw gcException(ERR_BADRESPONSE); if (UTIL::MISC::isValidImage((const unsigned char*)hh->getData()) == IMAGE_VOID) throw gcException(ERR_INVALIDDATA, gcString("The url {0} is not a valid image format", imageUrl)); UTIL::FS::Path path(appDataPath, fileName, false); UTIL::FS::recMakeFolder(path); UTIL::FS::FileHandle fh(path, UTIL::FS::FILE_WRITE); fh.write(hh->getData(), hh->getDataSize()); dii->outPath = path.getFullPath(); m_ImageCache.updateImagePath(dii->outPath.c_str(), hash); }
void QMLManager::checkCredentialsAndExecute(execute_function_type execute) { // if the cloud credentials are present, we should try to get the GPS Webservice ID // and (if we haven't done so) load the dive list if (!same_string(prefs.cloud_storage_email, "") && !same_string(prefs.cloud_storage_password, "")) { setAccessingCloud(0); setStartPageText(tr("Testing cloud credentials")); appendTextToLog("Have credentials, let's see if they are valid"); CloudStorageAuthenticate *csa = new CloudStorageAuthenticate(this); csa->backend(prefs.cloud_storage_email, prefs.cloud_storage_password, cloudPin()); // let's wait here for the signal to avoid too many more nested functions QTimer myTimer; myTimer.setSingleShot(true); QEventLoop loop; connect(csa, &CloudStorageAuthenticate::finishedAuthenticate, &loop, &QEventLoop::quit); connect(&myTimer, &QTimer::timeout, &loop, &QEventLoop::quit); myTimer.start(5000); loop.exec(); if (!myTimer.isActive()) { // got no response from the server setStartPageText(RED_FONT + tr("No response from cloud server to validate the credentials") + END_FONT); revertToNoCloudIfNeeded(); return; } myTimer.stop(); setCloudPin(""); if (prefs.cloud_verification_status != CS_VERIFIED) { // here we need to enter the PIN appendTextToLog(QStringLiteral("Need to verify the email address - enter PIN in desktop app")); setStartPageText(RED_FONT + tr("Cannot connect to cloud storage - cloud account not verified") + END_FONT); revertToNoCloudIfNeeded(); setShowPin(true); return; } if (showPin()) setShowPin(false); // now check the redirect URL to make sure everything is set up on the cloud server connect(manager(), &QNetworkAccessManager::authenticationRequired, this, &QMLManager::provideAuth, Qt::UniqueConnection); QUrl url(CLOUDREDIRECTURL); request = QNetworkRequest(url); request.setRawHeader("User-Agent", getUserAgent().toUtf8()); request.setRawHeader("Accept", "text/html"); reply = manager()->get(request); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError))); connect(reply, &QNetworkReply::sslErrors, this, &QMLManager::handleSslErrors); connect(reply, &QNetworkReply::finished, this, execute, Qt::UniqueConnection); } }
TiXmlNode* WebCoreClass::postToServer(std::string url, std::string resource, PostMap &postData, TiXmlDocument &doc, bool useHTTPS) { gcString httpOut; { HttpHandle hh(url.c_str(), useHTTPS); if (useHTTPS) { hh->setUserAgent(getUserAgent()); #ifdef WIN32 hh->setCertFile(".\\data\\ca-bundle.crt"); #else hh->setCertFile("data/ca-bundle.crt"); #endif } else { setWCCookies(hh); } PostMap::iterator it = postData.begin(); while (it != postData.end()) { hh->addPostText(it->first.c_str(), it->second.c_str()); it++; } hh->postWeb(); if (hh->getDataSize() == 0) throw gcException(ERR_BADRESPONSE, "Data size was zero"); doc.LoadBuffer(const_cast<char*>(hh->getData()), hh->getDataSize(), TIXML_ENCODING_UTF8); if (m_bDebuggingOut) httpOut.assign(const_cast<char*>(hh->getData()), hh->getDataSize()); } TiXmlNode *uNode = doc.FirstChild(resource.c_str()); if (m_bDebuggingOut && !uNode) Warning(httpOut); XML::processStatus(doc, resource.c_str()); return uNode; }
/* tests if address of signaling is different from address in 1st Via field */ static Bool testSourceAddress(struct sip_msg* msg) { Bool diffIP, diffPort; int via1Port; diffIP = received_test(msg); if (isSIPAsymmetric(getUserAgent(msg))) { // ignore port test for asymmetric clients (it's always different) diffPort = False; } else { via1Port = (msg->via1->port ? msg->via1->port : SIP_PORT); diffPort = (msg->rcv.src_port != via1Port); } return (diffIP || diffPort); }
GpsLocation::GpsLocation(void (*showMsgCB)(const char *), QObject *parent) : QObject(parent), m_GpsSource(0), waitingForPosition(false), haveSource(UNKNOWN) { Q_ASSERT_X(m_Instance == NULL, "GpsLocation", "GpsLocation recreated"); m_Instance = this; showMessageCB = showMsgCB; // create a QSettings object that's separate from the main application settings geoSettings = new QSettings(QSettings::NativeFormat, QSettings::UserScope, QString("org.subsurfacedivelog"), QString("subsurfacelocation"), this); userAgent = getUserAgent(); (void)getGpsSource(); loadFromStorage(); // register changes in time threshold connect(qPrefLocationService::instance(), SIGNAL(time_thresholdChanged(int)), this, SLOT(setGpsTimeThreshold(int))); }
bool CheckCloudConnection::checkServer() { QTimer timer; timer.setSingleShot(true); QEventLoop loop; QNetworkRequest request; request.setRawHeader("Accept", "text/plain"); request.setRawHeader("User-Agent", getUserAgent().toUtf8()); request.setUrl(QString(prefs.cloud_base_url) + TEAPOT); QNetworkAccessManager *mgr = new QNetworkAccessManager(); reply = mgr->get(request); connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrors(QList<QSslError>))); timer.start(2000); // wait two seconds loop.exec(); if (timer.isActive()) { // didn't time out, did we get the right response? timer.stop(); if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == HTTP_I_AM_A_TEAPOT && reply->readAll() == QByteArray(MILK)) { reply->deleteLater(); mgr->deleteLater(); if (verbose > 1) qWarning() << "Cloud storage: successfully checked connection to cloud server"; return true; } } else { disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit())); reply->abort(); } if (verbose) qDebug() << "connection test to cloud server failed" << reply->error() << reply->errorString() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << reply->readAll(); reply->deleteLater(); mgr->deleteLater(); if (verbose) qWarning() << "Cloud storage: unable to connect to cloud server"; return false; }
void QMLManager::checkCredentialsAndExecute(execute_function_type execute) { // if the cloud credentials are present, we should try to get the GPS Webservice ID // and (if we haven't done so) load the dive list if (!same_string(prefs.cloud_storage_email, "") && !same_string(prefs.cloud_storage_password, "")) { setAccessingCloud(0); setStartPageText(tr("Testing cloud credentials")); appendTextToLog("Have credentials, let's see if they are valid"); connect(manager(), &QNetworkAccessManager::authenticationRequired, this, &QMLManager::provideAuth, Qt::UniqueConnection); connect(manager(), &QNetworkAccessManager::finished, this, execute, Qt::UniqueConnection); QUrl url(CLOUDREDIRECTURL); request = QNetworkRequest(url); request.setRawHeader("User-Agent", getUserAgent().toUtf8()); request.setRawHeader("Accept", "text/html"); reply = manager()->get(request); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError))); connect(reply, &QNetworkReply::sslErrors, this, &QMLManager::handleSslErrors); } }
extern "C" void reverseGeoLookup(degrees_t latitude, degrees_t longitude, uint32_t uuid) { QNetworkRequest request; QNetworkAccessManager *rgl = new QNetworkAccessManager(); request.setUrl(QString("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=%1&lat=%2&lon=%3") .arg(uiLanguage(NULL)).arg(latitude.udeg / 1000000.0).arg(longitude.udeg / 1000000.0)); request.setRawHeader("Accept", "text/json"); request.setRawHeader("User-Agent", getUserAgent().toUtf8()); QNetworkReply *reply = rgl->get(request); QEventLoop loop; QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); QJsonParseError errorObject; QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &errorObject); if (errorObject.error != QJsonParseError::NoError) { qDebug() << errorObject.errorString(); } else { QJsonObject obj = jsonDoc.object(); QJsonObject address = obj.value("address").toObject(); qDebug() << "found country:" << address.value("country").toString(); struct dive_site *ds = get_dive_site_by_uuid(uuid); ds->notes = add_to_string(ds->notes, "countrytag: %s", address.value("country").toString().toUtf8().data()); } }
void UpdateManager::checkForUpdates(bool automatic) { QString os; #if defined(Q_OS_WIN) os = "win"; #elif defined(Q_OS_MAC) os = "osx"; #elif defined(Q_OS_LINUX) os = "linux"; #else os = "unknown"; #endif isAutomaticCheck = automatic; QString version = subsurface_canonical_version(); QString uuidString = getUUID(); QString url = QString("http://subsurface-divelog.org/updatecheck.html?os=%1&version=%2&uuid=%3").arg(os, version, uuidString); QNetworkRequest request; request.setUrl(url); request.setRawHeader("Accept", "text/xml"); QString userAgent = getUserAgent(); request.setRawHeader("User-Agent", userAgent.toUtf8()); connect(SubsurfaceWebServices::manager()->get(request), SIGNAL(finished()), this, SLOT(requestReceived()), Qt::UniqueConnection); }
static int UseMediaProxy(struct sip_msg* msg, char* str1, char* str2) { str sdp, sessionIP, signalingIP, callId, userAgent, tokens[64]; str fromDomain, toDomain, fromAddr, toAddr, fromTag, toTag, domain; char *ptr, *command, *result, *agent, *fromType, *toType, *info; int streamCount, i, port, count, portCount, cmdlen, infolen, status; StreamInfo streams[64], stream; Bool request; if (msg->first_line.type == SIP_REQUEST) { request = True; } else if (msg->first_line.type == SIP_REPLY) { request = False; } else { return -1; } if (!getCallId(msg, &callId)) { LM_ERR("can't get Call-Id\n"); return -1; } status = getSDPMessage(msg, &sdp); // status = -1 is error, -2 is missing SDP body if (status < 0) return status; if (!getSessionLevelMediaIP(&sdp, &sessionIP)) { LM_ERR("failed to parse the SDP message\n"); return -1; } streamCount = getMediaStreams(&sdp, &sessionIP, streams, 64); if (streamCount == -1) { LM_ERR("can't extract media streams from the SDP message\n"); return -1; } if (streamCount == 0) return 1; // there are no media streams. we have nothing to do. fromDomain = getFromDomain(msg); fromType = (isFromLocal(msg, NULL, NULL)>0) ? "local" : "remote"; fromAddr = getFromAddress(msg); toAddr = getToAddress(msg); fromTag = getFromTag(msg); toTag = getToTag(msg); userAgent = getUserAgent(msg); if (request) { toDomain = getDestinationDomain(msg); // call only for requests toType = (isDestinationLocal(msg, NULL, NULL)>0) ? "local" : "remote"; } else { toDomain.s = "unknown"; toDomain.len = 7; toType = "unknown"; } signalingIP = getSignalingIP(msg); domain = getMediaproxyDomain(msg); infolen = fromAddr.len + toAddr.len + fromTag.len + toTag.len + domain.len + 64; cmdlen = callId.len + signalingIP.len + fromDomain.len + toDomain.len + userAgent.len*3 + infolen + 128; for (i=0; i<streamCount; i++) { stream = streams[i]; cmdlen += stream.ip.len + stream.port.len + stream.type.len + 4; } command = pkg_malloc(cmdlen); if (!command) { LM_ERR("out of memory\n"); return -1; } if (request) count = sprintf(command, "request %.*s", callId.len, callId.s); else count = sprintf(command, "lookup %.*s", callId.len, callId.s); for (i=0, ptr=command+count; i<streamCount; i++) { char c = (i==0 ? ' ' : ','); count = sprintf(ptr, "%c%.*s:%.*s:%.*s", c, streams[i].ip.len, streams[i].ip.s, streams[i].port.len, streams[i].port.s, streams[i].type.len, streams[i].type.s); ptr += count; } agent = encodeQuopri(userAgent); if (!agent) { LM_ERR("out of memory\n"); pkg_free(command); return -1; } info = pkg_malloc(infolen); if (!info) { LM_ERR("out of memory\n"); pkg_free(command); pkg_free(agent); return -1; } sprintf(info, "from:%.*s,to:%.*s,fromtag:%.*s,totag:%.*s", fromAddr.len, fromAddr.s, toAddr.len, toAddr.s, fromTag.len, fromTag.s, toTag.len, toTag.s); if (domain.len) { strcat(info, ",domain:"); strncat(info, domain.s, domain.len); } if (isRTPAsymmetric(userAgent)) { strcat(info, ",asymmetric"); } snprintf(ptr, command + cmdlen - ptr, " %.*s %.*s %s %.*s %s %s info=%s\n", signalingIP.len, signalingIP.s, fromDomain.len, fromDomain.s, fromType, toDomain.len, toDomain.s, toType, agent, info); pkg_free(info); pkg_free(agent); result = sendMediaproxyCommand(command); pkg_free(command); if (result == NULL) return -1; count = getTokens(result, tokens, sizeof(tokens)/sizeof(str)); if (count == 0) { LM_ERR("empty response from mediaproxy\n"); return -1; } else if (count<streamCount+1) { if (request) { LM_ERR("insufficient ports returned from mediaproxy: got %d, " "expected %d\n", count-1, streamCount); return -1; } else { LM_WARN("broken client. Called UA added extra media stream(s) " "in the OK reply\n"); } } if (sessionIP.s && !isAnyAddress(sessionIP)) { if (!replaceElement(msg, &sessionIP, &tokens[0])) { LM_ERR("failed to replace session-level media IP in the SDP body\n"); return -1; } } portCount = min(count-1, streamCount); for (i=0; i<portCount; i++) { // check. is this really necessary? port = strtoint(&tokens[i+1]); if (port <= 0 || port > 65535) { LM_ERR("invalid port returned by mediaproxy: %.*s\n", tokens[i+1].len, tokens[i+1].s); //return -1; continue; } if (streams[i].port.len!=1 || streams[i].port.s[0]!='0') { if (!replaceElement(msg, &(streams[i].port), &tokens[i+1])) { LM_ERR("failed to replace port in media stream number %d\n", i+1); return -1; } } if (streams[i].localIP && !isAnyAddress(streams[i].ip)) { if (!replaceElement(msg, &(streams[i].ip), &tokens[0])) { LM_ERR("failed to replace IP address in media stream number %d\n", i+1); return -1; } } } return 1; }
// TODO(jat): remove suppliedUrl and update hosted.html API NS_IMETHODIMP ExternalWrapper::Connect(const nsACString& suppliedUrl, const nsACString& sessionKey, const nsACString& aAddr, const nsACString& aModuleName, const nsACString& hostedHtmlVersion, PRBool *_retval) { Debug::log(Debug::Info) << "Connect(url=" << url << ", sessionKey=" << sessionKey << ", address=" << aAddr << ", module=" << aModuleName << ", hostedHtmlVersion=" << hostedHtmlVersion << Debug::flush; // TODO: string utilities? nsCString urlAutoStr; NS_UTF16ToCString(url, NS_CSTRING_ENCODING_UTF8, urlAutoStr); nsCString sessionKeyAutoStr(sessionKey); nsCString addrAutoStr(aAddr); nsCString moduleAutoStr(aModuleName); nsCString hostedHtmlVersionAutoStr(hostedHtmlVersion); std::string hostedUrl(addrAutoStr.get()); std::string urlStr(urlAutoStr.get()); bool allowed = false; std::string webHost = AllowedConnections::getHostFromUrl(urlStr); std::string codeServer = AllowedConnections::getCodeServerFromUrl(urlStr); if (!AllowedConnections::matchesRule( webHost, codeServer, &allowed)) { // If we didn't match an existing rule, prompt the user allowed = askUserToAllow(urlStr); } if (!allowed) { *_retval = false; return NS_OK; } size_t index = hostedUrl.find(':'); if (index == std::string::npos) { *_retval = false; return NS_OK; } std::string hostPart = hostedUrl.substr(0, index); std::string portPart = hostedUrl.substr(index + 1); // TODO(jat): leaks HostChannel -- need to save it in a session object and // return that so the host page can call a disconnect method on it at unload // time or when it gets GC'd. HostChannel* channel = new HostChannel(); Debug::log(Debug::Debugging) << "Connecting..." << Debug::flush; if (!channel->connectToHost(hostPart.c_str(), atoi(portPart.c_str()))) { *_retval = false; return NS_OK; } Debug::log(Debug::Debugging) << "...Connected" << Debug::flush; sessionHandler.reset(new FFSessionHandler(channel/*, ctx*/)); std::string hostedHtmlVersionStr(hostedHtmlVersionAutoStr.get()); if (!channel->init(sessionHandler.get(), BROWSERCHANNEL_PROTOCOL_VERSION, BROWSERCHANNEL_PROTOCOL_VERSION, hostedHtmlVersionStr)) { *_retval = false; return NS_OK; } std::string moduleName(moduleAutoStr.get()); std::string userAgent; // get the user agent nsresult res = getUserAgent(userAgent); if (NS_FAILED(res)) { return res; } std::string tabKeyStr = computeTabIdentity(); std::string sessionKeyStr(sessionKeyAutoStr.get()); LoadModuleMessage::send(*channel, urlStr, tabKeyStr, sessionKeyStr, moduleName, userAgent, sessionHandler.get()); // TODO: return session object? *_retval = true; return NS_OK; }
static int UseMediaProxy(struct sip_msg* msg, char* str1, char* str2) { str sdp, sessionIP, callId, fromDomain, toDomain, userAgent, tokens[64]; str fromAddr, toAddr, fromTag, toTag; char *clientIP, *ptr, *command, *result, *agent, *fromType, *toType, *info; int streamCount, i, port, count, portCount, cmdlen, infolen, success, type; StreamInfo streams[64], stream; Bool request; if (msg->first_line.type == SIP_REQUEST) { if (msg->first_line.u.request.method_value == METHOD_INVITE) type = MSG_INVITE; else if (msg->first_line.u.request.method_value == METHOD_ACK) type = MSG_ACK; else type = MSG_UNKNOWN; } else if (msg->first_line.type == SIP_REPLY) { type = MSG_REPLY; } else { type = MSG_UNKNOWN; } if (type==MSG_INVITE || type==MSG_ACK) { request = True; } else if (type==MSG_REPLY) { request = False; } else { return -1; } if (!getCallId(msg, &callId)) { LOG(L_ERR, "error: use_media_proxy(): can't get Call-Id\n"); return -1; } success = getSDPMessage(msg, &sdp); if (success==0 && type==MSG_ACK) { return 1; // nothing to do. it's ok for ACK to not have a SDP body } else if (success <= 0) { LOG(L_ERR, "error: use_media_proxy(): failed to get the SDP message\n"); return -1; } if (!getSessionLevelMediaIP(&sdp, &sessionIP)) { LOG(L_ERR, "error: use_media_proxy(): error parsing the SDP message\n"); return -1; } streamCount = getMediaStreams(&sdp, &sessionIP, streams, 64); if (streamCount == -1) { LOG(L_ERR, "error: use_media_proxy(): can't extract media streams " "from the SDP message\n"); return -1; } if (streamCount == 0) { // there are no media streams. we have nothing to do. return 1; } fromDomain = getFromDomain(&fromType, msg); fromAddr = getFromAddress(msg); toAddr = getToAddress(msg); fromTag = getFromTag(msg); toTag = getToTag(msg); userAgent = getUserAgent(msg); if (request) { toDomain = getDestinationDomain(&toType, msg); // call only for requests } else { toDomain = getToDomain(&toType, msg); } clientIP = ip_addr2a(&msg->rcv.src_ip); infolen = fromAddr.len + toAddr.len + fromTag.len + toTag.len + 64; cmdlen = callId.len + strlen(clientIP) + fromDomain.len + toDomain.len + userAgent.len*3 + infolen + 128; for (i=0; i<streamCount; i++) { stream = streams[i]; cmdlen += stream.ip.len + stream.port.len + stream.type.len + 4; } command = pkg_malloc(cmdlen); if (!command) { LOG(L_ERR, "error: use_media_proxy(): out of memory\n"); return -1; } if (request) count = sprintf(command, "request %.*s", callId.len, callId.s); else count = sprintf(command, "lookup %.*s", callId.len, callId.s); for (i=0, ptr=command+count; i<streamCount; i++) { char c = (i==0 ? ' ' : ','); count = sprintf(ptr, "%c%.*s:%.*s:%.*s", c, streams[i].ip.len, streams[i].ip.s, streams[i].port.len, streams[i].port.s, streams[i].type.len, streams[i].type.s); ptr += count; } agent = encodeQuopri(userAgent); if (!agent) { LOG(L_ERR, "error: use_media_proxy(): out of memory\n"); pkg_free(command); return -1; } info = pkg_malloc(infolen); if (!info) { LOG(L_ERR, "error: use_media_proxy(): out of memory\n"); pkg_free(command); pkg_free(agent); return -1; } sprintf(info, "from:%.*s,to:%.*s,fromtag:%.*s,totag:%.*s", fromAddr.len, fromAddr.s, toAddr.len, toAddr.s, fromTag.len, fromTag.s, toTag.len, toTag.s); if (isRTPAsymmetric(userAgent)) { strcat(info, ",asymmetric"); } snprintf(ptr, command + cmdlen - ptr, " %s %.*s %s %.*s %s %s info=%s\n", clientIP, fromDomain.len, fromDomain.s, fromType, toDomain.len, toDomain.s, toType, agent, info); pkg_free(info); pkg_free(agent); result = sendMediaproxyCommand(command); pkg_free(command); if (result == NULL) return -1; count = getTokens(result, tokens, sizeof(tokens)/sizeof(str)); if (count == 0) { LOG(L_ERR, "error: use_media_proxy(): empty response from mediaproxy\n"); return -1; } else if (count<streamCount+1) { if (request) { LOG(L_ERR, "error: use_media_proxy(): insufficient ports returned " "from mediaproxy: got %d, expected %d\n", count-1, streamCount); return -1; } else { LOG(L_WARN, "warning: use_media_proxy(): broken client. Called UA " "added extra media stream(s) in the OK reply\n"); } } if (sessionIP.s && !isAnyAddress(sessionIP)) { success = replaceElement(msg, &sessionIP, &tokens[0]); if (!success) { LOG(L_ERR, "error: use_media_proxy(): failed to replace " "session-level media IP in SDP body\n"); return -1; } } portCount = min(count-1, streamCount); for (i=0; i<portCount; i++) { // check. is this really necessary? port = strtoint(&tokens[i+1]); if (port <= 0 || port > 65535) { LOG(L_ERR, "error: use_media_proxy(): invalid port returned " "by mediaproxy: %.*s\n", tokens[i+1].len, tokens[i+1].s); //return -1; continue; } if (streams[i].port.len!=1 || streams[i].port.s[0]!='0') { success = replaceElement(msg, &(streams[i].port), &tokens[i+1]); if (!success) { LOG(L_ERR, "error: use_media_proxy(): failed to replace " "port in media stream nr. %d\n", i+1); return -1; } } if (streams[i].localIP && !isAnyAddress(streams[i].ip)) { success = replaceElement(msg, &(streams[i].ip), &tokens[0]); if (!success) { LOG(L_ERR, "error: use_media_proxy(): failed to replace " "IP address in media stream nr. %d\n", i+1); return -1; } } } return 1; }
void ReverseGeoLookupThread::run() { if (geo_lookup_data.isEmpty()) return; QNetworkRequest request; QNetworkAccessManager *rgl = new QNetworkAccessManager(); QEventLoop loop; QString mapquestURL("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=%1&lat=%2&lon=%3"); QString geonamesURL("http://api.geonames.org/findNearbyPlaceNameJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh"); QString geonamesOceanURL("http://api.geonames.org/oceanJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh"); QString divelogsURL("https://www.divelogs.de/mapsearch_divespotnames.php?lat=%1&lng=%2&radius=50"); QTimer timer; request.setRawHeader("Accept", "text/json"); request.setRawHeader("User-Agent", getUserAgent().toUtf8()); connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); Q_FOREACH (const GeoLookupInfo& info, geo_lookup_data ) { struct dive_site *ds = info.uuid ? get_dive_site_by_uuid(info.uuid) : &displayed_dive_site; // first check the findNearbyPlaces API from geonames - that should give us country, state, city request.setUrl(geonamesURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0)); QNetworkReply *reply = rgl->get(request); timer.setSingleShot(true); connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); timer.start(5000); // 5 secs. timeout loop.exec(); if(timer.isActive()) { timer.stop(); if(reply->error() > 0) { report_error("got error accessing geonames.org: %s", qPrintable(reply->errorString())); goto clear_reply; } int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (v < 200 || v >= 300) goto clear_reply; QByteArray fullReply = reply->readAll(); QJsonParseError errorObject; QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject); if (errorObject.error != QJsonParseError::NoError) { report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString())); goto clear_reply; } QJsonObject obj = jsonDoc.object(); QVariant geoNamesObject = obj.value("geonames").toVariant(); QVariantList geoNames = geoNamesObject.toList(); if (geoNames.count() > 0) { QVariantMap firstData = geoNames.at(0).toMap(); int ri = 0, l3 = -1, lt = -1; if (ds->taxonomy.category == NULL) { ds->taxonomy.category = alloc_taxonomy(); } else { // clear out the data (except for the ocean data) int ocean; if ((ocean = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN)) > 0) { ds->taxonomy.category[0] = ds->taxonomy.category[ocean]; ds->taxonomy.nr = 1; } else { // ocean is -1 if there is no such entry, and we didn't copy above // if ocean is 0, so the following gets us the correct count ds->taxonomy.nr = ocean + 1; } } // get all the data - OCEAN is special, so start at COUNTRY for (int j = TC_COUNTRY; j < TC_NR_CATEGORIES; j++) { if (firstData[taxonomy_api_names[j]].isValid()) { ds->taxonomy.category[ri].category = j; ds->taxonomy.category[ri].origin = taxonomy::GEOCODED; free((void*)ds->taxonomy.category[ri].value); ds->taxonomy.category[ri].value = copy_string(qPrintable(firstData[taxonomy_api_names[j]].toString())); ri++; } } ds->taxonomy.nr = ri; l3 = taxonomy_index_for_category(&ds->taxonomy, TC_ADMIN_L3); lt = taxonomy_index_for_category(&ds->taxonomy, TC_LOCALNAME); if (l3 == -1 && lt != -1) { // basically this means we did get a local name (what we call town), but just like most places // we didn't get an adminName_3 - which in some regions is the actual city that town belongs to, // then we copy the town into the city ds->taxonomy.category[ri].value = copy_string(ds->taxonomy.category[lt].value); ds->taxonomy.category[ri].origin = taxonomy::COPIED; ds->taxonomy.category[ri].category = TC_ADMIN_L3; ds->taxonomy.nr++; } mark_divelist_changed(true); } else { report_error("geonames.org did not provide reverse lookup information"); qDebug() << "no reverse geo lookup; geonames returned\n" << fullReply; } } else { report_error("timeout accessing geonames.org"); disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit())); reply->abort(); } // next check the oceans API to figure out the body of water request.setUrl(geonamesOceanURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0)); reply = rgl->get(request); connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); timer.start(5000); // 5 secs. timeout loop.exec(); if(timer.isActive()) { timer.stop(); if(reply->error() > 0) { report_error("got error accessing oceans API of geonames.org: %s", qPrintable(reply->errorString())); goto clear_reply; } int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (v < 200 || v >= 300) goto clear_reply; QByteArray fullReply = reply->readAll(); QJsonParseError errorObject; QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject); if (errorObject.error != QJsonParseError::NoError) { report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString())); goto clear_reply; } QJsonObject obj = jsonDoc.object(); QVariant oceanObject = obj.value("ocean").toVariant(); QVariantMap oceanName = oceanObject.toMap(); if (oceanName["name"].isValid()) { int idx; if (ds->taxonomy.category == NULL) ds->taxonomy.category = alloc_taxonomy(); idx = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN); if (idx == -1) idx = ds->taxonomy.nr; if (idx < TC_NR_CATEGORIES) { ds->taxonomy.category[idx].category = TC_OCEAN; ds->taxonomy.category[idx].origin = taxonomy::GEOCODED; ds->taxonomy.category[idx].value = copy_string(qPrintable(oceanName["name"].toString())); if (idx == ds->taxonomy.nr) ds->taxonomy.nr++; } mark_divelist_changed(true); } } else { report_error("timeout accessing geonames.org"); disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit())); reply->abort(); } clear_reply: reply->deleteLater(); } rgl->deleteLater(); }