void MTD_FLASHMEM HTTPGPIOConfigurationResponse::flush()
 {
     if (getRequest().method == HTTPHandler::Post)
     {
         char const* gpio = getRequest().form[FSTR("GPIO")];
         if (getRequest().form[FSTR("configured")])
         {		
             // gpio enabled
             char const* mode     = getRequest().form[STR_mode];
             char const* pullUp   = getRequest().form[STR_pullup];
             ConfigurationManager::setGPIOParams(strtol(gpio, NULL, 10), true, f_strcmp(mode, STR_out) == 0, pullUp != NULL, false);
             ConfigurationManager::applyGPIO();
         }
         else if (gpio)
         {
             // gpio disabled (not configured)
             ConfigurationManager::setGPIOParams(strtol(gpio, NULL, 10), false, false, false, false);
         }
     }
     
     HTTPHelperConfiguration::GPIOSetValue(this);
     
     LinkedCharChunks* linkedChunks = addParamCharChunks(FSTR("GPIOS"));
     for (uint32_t i = 0; i != 16; ++i)
     {
         if (i != 1 && i != 3 && (i < 6 || i > 11))
         {
             bool configured, isOutput, pullUp, value;
             ConfigurationManager::getGPIOParams(i, &configured, &isOutput, &pullUp, &value);
             
             linkedChunks->addChunk(f_printf(FSTR("<tr> <td>%d</td> <td><form method='POST'>"), i), true);
             linkedChunks->addChunk(f_printf(FSTR("Enabled <input type='checkbox' name='configured' value='1' onclick=\"document.getElementById('GPIO%d').disabled=!this.checked\" %s>"), i, configured? STR_checked:STR_), true);
             linkedChunks->addChunk(f_printf(FSTR("<fieldset class='inline' id='GPIO%d' %s>"), i, configured? STR_:STR_disabled), true);
             linkedChunks->addChunk(f_printf(FSTR("<select name='mode'><option value='in' %s>IN</option><option value='out' %s>OUT</option></select>"), 
                                            isOutput? STR_:STR_selected, 
                                            isOutput? STR_selected:STR_), 
                                   true);
             linkedChunks->addChunk(f_printf(FSTR("     PullUp <input type='checkbox' name='pullup' value='1' %s> </fieldset>"), pullUp? STR_checked:STR_), true);
             linkedChunks->addChunk(f_printf(FSTR("<input type='hidden' name='GPIO' value='%d'>"), i), true);
             linkedChunks->addChunk(FSTR("<input type='submit' value='Save'></form></td>"));
             if (configured)
             {
                 if (isOutput)
                 {
                     linkedChunks->addChunk(f_printf(FSTR("<td><a href='confgpio?gpio=%d&val=%d&store=1' class='link_button2'>%s</a></td> </tr>"), i, !value, value? STR_HI:STR_LO), true);
                 }
                 else
                 {
                     linkedChunks->addChunk(f_printf(FSTR("<td>%s</td> </tr>"), GPIO(i).read()? STR_HI:STR_LO), true);
                 }
             }
             else
             {
                 linkedChunks->addChunk(FSTR("<td></td></tr>"));
             }
         }
     }			
         
     HTTPTemplateResponse::flush();
 }
Beispiel #2
0
void Server::worker (int id) {
  bool moreToReceive;
  bool moreToSend;
  pb::RequestEnvelope requestEnvelope;
  pb::ReplyEnvelope replyEnvelope;
  zmq::socket_t socket (*context, ZMQ_REP);
  
  socket.connect (workerConn.c_str ());
  while (true) {    
    moreToReceive = getRequest (socket, requestEnvelope);
    
    // creating appropriate service to handle request
    TServiceMap::iterator it = serviceMap.find (requestEnvelope.service ());
    bool notInMap = (it == serviceMap.end());
    scoped_ptr<IService> service (notInMap ? new NotImplemented : it->second ());  
    
    std::cout << id << ": " << requestEnvelope.service () << " -> " << 
      service->getService () << "\n";
    service->setRequest (requestEnvelope, moreToReceive);
    requestEnvelope.Clear ();
    
    while (moreToReceive) {
      moreToReceive = getRequest (socket, requestEnvelope);
      service->setRequest (requestEnvelope, moreToReceive);
      requestEnvelope.Clear ();
    }
    
    do {
      moreToSend = service->getReply (replyEnvelope);
      sendReply (socket, replyEnvelope, moreToSend);
      replyEnvelope.Clear ();
    } while (moreToSend);
  }
}
    void MTD_FLASHMEM HTTPGPIOResponseHTML::flush()
    {
        setStatus(STR_200_OK);
        addHeader(STR_Content_Type, STR_TEXTHTML);

        char const* cmd = getRequest().query[FSTR("cmd")];
        if (cmd && f_strcmp(cmd, FSTR("set")) == 0)
        {
            // set gpio
            HTTPHelperConfiguration::GPIOSetValue(this);
        }
        else if (cmd && f_strcmp(cmd, FSTR("conf")) == 0)
        {
            // conf gpio
            HTTPHelperConfiguration::GPIOConf(this);
        }
        
        char const* gpio = getRequest().query[STR_gpio];
        if (gpio)
        {
            uint8_t gpion = strtol(gpio, NULL, 10);
            addContent(GPIO(gpion).read()? STR_1 : STR_0);
        }
        
        HTTPResponse::flush();
    }
/*virtual*/
void LLObjectMediaNavigateClient::Responder::result(const LLSD& content)
{
	LL_INFOS("LLMediaDataClient") << *(getRequest()) << " NAVIGATE returned " << ll_print_sd(content) << LL_ENDL;
	
	if (content.has("error"))
	{
		const LLSD &error = content["error"];
		int error_code = error["code"];
		
		if (ERROR_PERMISSION_DENIED_CODE == error_code)
		{
			LL_WARNS("LLMediaDataClient") << *(getRequest()) << " Navigation denied: bounce back" << LL_ENDL;
			const LLSD &payload = getRequest()->getPayload();
			// bounce the face back
			getRequest()->getObject()->mediaNavigateBounceBack((LLSD::Integer)payload[LLTextureEntry::TEXTURE_INDEX_KEY]);
		}
		else {
			LL_WARNS("LLMediaDataClient") << *(getRequest()) << " Error navigating: code=" << 
				error["code"].asString() << ": " << error["message"].asString() << LL_ENDL;
		}			 
		// XXX Warn user?
	}
	else {
		// just do what our superclass does
		LLMediaDataClient::Responder::result(content);
	}
}
const UserUser*
RequestData::getUser() const
{
   if ( getRequest() ) {
      return getRequest()->getUser();
   } else {      
      return m_user;
   }
}
Beispiel #6
0
String HtmlTabCtrl::getPageLink(uint32 index)
{
	OS_EXCEPT_IF(hasID() == false, "Invalid tabctrl id");
	OS_EXCEPT_IF(getRequest() == nullptr, "Invalid request object");

	ordered_map<std::wstring, std::wstring> params(getRequest()->getUrlParams());
	params.set(getTarget().to_wide(), conversions::to_wstring(index));

	return HttpParser::generateLink(getRequest()->getRawUrl(), params);
}
Beispiel #7
0
void *clientThread(void *data)
{
	threadStart();
	pthread_t pthread_self();
	pid_t clientPid = *(pid_t *)data, secondClientPid = 0;
	int k = 0, n = 0, m = 0;
	long msgType = clientPid, secondMsgType = 0;
	getRequest(msgType, &k, &n);
	if (getPartner(clientPid, &secondClientPid, k, n, &m) == 1)
		sendErrorInfo(msgType);
	if (secondClientPid != clientPid) {
		secondMsgType = secondClientPid;
		if (getResources(clientPid, secondClientPid, k, n, m) == 0) {
			sendResources(msgType, secondClientPid);
			sendResources(secondMsgType, clientPid);
			getResourcesBack(msgType, secondMsgType, k, n + m);
		} else {
			sendErrorInfo(msgType);
			sendErrorInfo(secondMsgType);
		}
	}
	free(data);
	threadEnd();
	return 0;
}
Beispiel #8
0
MojErr MojService::dispatchReply(MojServiceMessage* msg)
{
	MojAssert(msg);
	MojAssertMutexUnlocked(m_mutex);
	MojLogTrace(s_log);

	// parse payload
	MojObjectBuilder builder;
	MojObject payload;
	MojErr err = MojErrNone;
	MojInt64 errCode = MojErrNone;
	errCode = err = msg->payload(builder);
	MojErrCatchAll(err);
	if (errCode == MojErrNone)
		payload = builder.object();

	// get errCode
	bool retVal = false;
	if (payload.get(MojServiceMessage::ReturnValueKey, retVal) && !retVal) {
		if (!payload.get(MojServiceMessage::ErrorCodeKey, errCode))
			errCode = MojErrUnknown;
	}
	// find request
	MojRefCountedPtr<MojServiceRequest> req;
	err = getRequest(msg, req);
	MojErrCheck(err);

	// do the dispatch
	err = dispatchReplyImpl(req.get(), msg, payload, (MojErr) errCode);
	MojErrCatchAll(err);

	return MojErrNone;
}
 void MTD_FLASHMEM HTTPWifiConfigurationResponse::flush()
 {
     if (getRequest().method == HTTPHandler::Post)
     {
         // set WiFi mode
         HTTPHelperConfiguration::setWiFiMode(this);
         
         // set client mode WiFi parameters
         HTTPHelperConfiguration::setClientModeWiFiParams(this);
         
         // set access point parameters
         HTTPHelperConfiguration::setAPWiFiParams(this);
     }
     
     // get WiFi mode
     HTTPHelperConfiguration::getWiFiMode(this);
     
     // get client mode WiFi parameters
     HTTPHelperConfiguration::getClientModeWiFiParams(this);
     
     // get access point parameters
     APtr<char> APCHStr, APSECStr;
     HTTPHelperConfiguration::getAPWiFiParams(this, APCHStr, APSECStr);
     
     HTTPTemplateResponse::flush();
 }
Beispiel #10
0
int main(int argc, char* argv[]) {

	int port;
	int serverSocket, clientSocket;
	struct httpParams httpParam;
	
	system("clear");	

	if (argc != 2) {
		fprintf(stderr, "Usage: %s <Server Port>\n", argv[0]);
		exit(1);
	}

	port = atoi(argv[1]);

	serverSocket = initializeServer(port);	

	while(1) {
	
		clientSocket = getRequest(serverSocket);
		readFromClient(clientSocket);
		httpParam = prepareGetQuery();
		sendToClient(clientSocket, httpParam);
		
		exit(1);

	}
}
/*virtual*/
void LLObjectMediaNavigateClient::Responder::error(U32 status, const std::string& reason)
{
	// Bounce back (unless HTTP_SERVICE_UNAVAILABLE, in which case call base
	// class
	if (status == HTTP_SERVICE_UNAVAILABLE)
	{
		LLMediaDataClient::Responder::error(status, reason);
	}
	else {
		// bounce the face back
		LL_WARNS("LLMediaDataClient") << *(getRequest()) << " Error navigating: http code=" << status << LL_ENDL;
		const LLSD &payload = getRequest()->getPayload();
		// bounce the face back
		getRequest()->getObject()->mediaNavigateBounceBack((LLSD::Integer)payload[LLTextureEntry::TEXTURE_INDEX_KEY]);
	}
}
void GetInstanceResponseHandler::deliver(const CIMInstance& cimInstance)
{
    if (cimInstance.isUninitialized())
    {
        MessageLoaderParms message(
            "Common.Exception.UNINITIALIZED_OBJECT_EXCEPTION",
            "The object is not initialized.");

        throw CIMException(CIM_ERR_FAILED, message);
    }

    if (SimpleInstanceResponseHandler::size() != 0)
    {
        MessageLoaderParms message(
            "Server.OperationResponseHandler.TOO_MANY_OBJECTS_DELIVERED",
            "Too many objects delivered.");

        throw CIMException(CIM_ERR_FAILED, message);
    }

    CIMInstance localInstance(cimInstance);
#ifdef PEGASUS_ENABLE_OBJECT_NORMALIZATION
    // The normalizer expects an object path embedded in instances even
    // though it is not required by this operation. Use the requested
    // object path is missing from the instance.
    if (localInstance.getPath().getKeyBindings().size() == 0)
    {
        // ATTN: should clone before modification
        localInstance.setPath(static_cast<CIMGetInstanceRequestMessage*>(
            getRequest())->instanceName);
    }
#endif
    SimpleInstanceResponseHandler::deliver(
        _normalizer.processInstance(localInstance));
}
void SNMPRemoteAgent::cancelRequest(int id) {
	SNMPRequest* pRequest = getRequest(id);
	if(pRequest) {
		SnmpCancelMsg(_pSession->getHandle(), id);
		removeFromRequestMap(id);
	}
}
void DetermineAuthTypeJob::start()
{
    QNetworkReply *reply = getRequest(account()->davPath());
    setReply(reply);
    setupConnections(reply);
    AbstractNetworkJob::start();
}
void Client::setup()
{
    authenticated = false;
    error = false;

    buttonTimeout = new QTimer(this);
    connect(buttonTimeout,SIGNAL(timeout()),this,SLOT(exhibitNumberEntered()));
    buttonTimeout->setSingleShot(true);

//    lcd = new LcdController();
    mediaPlayer = new MediaPlayer();
    keypad = new KeypadController();

    // must register own types or Qt wont connect them properly
    qRegisterMetaType<KeypadButton>("KeypadButton");

    QObject::connect(this, SIGNAL(getPin()), keypad, SLOT(pinRequested()));
    QObject::connect(keypad, SIGNAL(forwardButton(KeypadButton)), this, SLOT(buttonPressed(KeypadButton)));
    QObject::connect(keypad, SIGNAL(forwardPincode(QString)), this, SLOT(pincodeReceived(QString)));

    // network lives in a thread so hook up signals
    network = new Network();
    QObject::connect(this, SIGNAL(request(QUrl, QString)), network, SLOT(getRequest(QUrl, QString)));
    QObject::connect(network, SIGNAL(forwardMessage(QString, unsigned int)), this, SLOT(networkReply(QString, unsigned int)));

    // setup location tracker thread
    tracker = new LocationTracker();
    QObject::connect(tracker, SIGNAL(forwardNewLocation(int)), this, SLOT(locationChanged(int)));
}
bool DetermineAuthTypeJob::finished()
{
    QUrl redirection = reply()->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    qDebug() << Q_FUNC_INFO << redirection.toString();
    if (_redirects >= maxRedirects()) {
        redirection.clear();
    }
    if ((reply()->error() == QNetworkReply::AuthenticationRequiredError) || redirection.isEmpty()) {
        emit authType(WizardCommon::HttpCreds);
    } else if (redirection.toString().endsWith(account()->davPath())) {
        // do a new run
        _redirects++;
        resetTimeout();
        setReply(getRequest(redirection));
        setupConnections(reply());
        return false; // don't discard
    } else {
        QRegExp shibbolethyWords("SAML|wayf");

        shibbolethyWords.setCaseSensitivity(Qt::CaseInsensitive);
        if (redirection.toString().contains(shibbolethyWords)) {
            emit authType(WizardCommon::Shibboleth);
        } else {
            // TODO: Send an error.
            // eh?
            emit authType(WizardCommon::HttpCreds);
        }
    }
    return true;
}
Beispiel #17
0
int32 FileDaemon::WaitOnRequests(void *arg) {
	FileDaemon *us = reinterpret_cast<FileDaemon *>(arg);
	status_t err = B_ERROR;
	BMessenger msgr(us);
	bool work = true;
	thread_id thread = find_thread(NULL);

	while (work) {
		snooze(kSnoozeTime);

		BMessage getRequest(kGetRequest);
		getRequest.AddInt32("threadid", thread);
		BMessage reply;

		if (msgr.SendMessage(&getRequest, &reply) != B_OK) {
			work = false;
			continue;
		};

		RequestInfo *info = NULL;
		reply.FindBool("continue", &work);
		
		if (reply.FindPointer("requestinfo", reinterpret_cast<void **>(&info)) != B_OK) continue;
		if (info == NULL) continue;

		status_t result = info->request->Start();

		// Send the complete/ error message
		if (info->target) {
			fprintf(stderr, "FileDaemon::WaitOnRequests(): %s: %s (%i)\n", info->request->URL(),
				strerror(result), result);
		
			switch (result) {
				case B_OK: {
					if (info->finish) info->target->SendMessage(info->finish);
				} break;
				
				case DownloadCancelled: {
					if (info->cancel) info->target->SendMessage(info->cancel);
				} break;
				
				default: {
					if (info->error) info->target->SendMessage(info->error);
				} break;
			};
		};

		BMessage requestComplete(kRequestComplete);
		requestComplete.AddInt32("threadid", thread);
		requestComplete.AddPointer("requestinfo", &info);
		
		msgr.SendMessage(&requestComplete);
	};

	BMessage threadComplete(kThreadComplete);
	threadComplete.AddInt32("threadid", thread);
	msgr.SendMessage(&threadComplete);
	
	return B_OK;
};
Beispiel #18
0
void ValidateDavAuthJob::start()
{
    QNetworkReply *reply = getRequest(Account::davPath());
    setReply(reply);
    setupConnections(reply);
    AbstractNetworkJob::start();
}
Beispiel #19
0
static void GPRS_Send(uint32_t address,uint8_t data_type, uint16_t data)
{
    setURL(address,data_type,data);
    delay_s(2);
    getRequest();
    delay_s(4);
    
}
Beispiel #20
0
QNetworkReply *ownCloudInfo::checkInstallation()
{
    _redirectCount = 0;
    MirallConfigFile cfgFile(  _configHandle );
    QUrl url ( cfgFile.ownCloudUrl( _connection ) +  QLatin1String("status.php") );
    /* No authentication required for this. */
    return getRequest(url);
}
Beispiel #21
0
QNetworkReply* ownCloudInfo::getWebDAVPath( const QString& path )
{
    _redirectCount = 0;
    QUrl url ( webdavUrl( _connection ) +  path );
    QNetworkReply *reply = getRequest(url);
    _directories[reply] = path;
    return reply;
}
void QPushbulletHandler::requestPushHistory(double modifiedAfter)
{
    m_CurrentOperation = CURRENT_OPERATION::GET_PUSH_HISTORY;
    QString url(m_URLPushes.toString());
    url.append("?modified_after=");
    url.append(QString::number(modifiedAfter));
    getRequest(QUrl(url));
}
Beispiel #23
0
void Request::handle( void ){
	if( getRequest() ){
		if( method == "GET" )
			processGet( true );
		if( method == "HEAD" ) 
			processGet( false);
	}
}
void ValidateDavAuthJob::start()
{
    QString p = account()->davPath();
    QNetworkReply *reply = getRequest(p);
    setReply(reply);
    setupConnections(reply);
    AbstractNetworkJob::start();
}
 HttpResponse CurlHttpHandler::getRequest(const string& requestUri,
     const pair<string, string>& singleHeader,
     bool withAbsolutePath)
 {
     vector<pair<string, string>> v;
     v.push_back(singleHeader);
     return getRequest(requestUri, v, withAbsolutePath);
 }
void vmsUrlMonRequestCollector::onInternetProtocolRoot_Abort(IInternetProtocolRoot *pProt, HRESULT hrReason, DWORD dwOptions)
{
	vmsCriticalSectionAutoLock csal (&m_csReq);
	int nIndex = findRequestIndexByProtocol (pProt);
	ATLASSERT (nIndex != -1);
	if (nIndex == -1)
		return;
	Request *req = getRequest (nIndex);
}
 // Initiates a simple GET request to the transport
 void SetUp() override {
   EXPECT_CALL(m_server, onRequest(_))
     .WillOnce(Invoke([] (std::shared_ptr<ProxygenTransport> transport) {
           transport->setEnqueued();
         }));
   auto req = getRequest(HTTPMethod::GET);
   m_transport->onHeadersComplete(std::move(req));
   m_transport->onEOM();
 }
Beispiel #28
0
bool CheckServerJob::finished()
{
    account()->setSslConfiguration(reply()->sslConfiguration());

    // ### the qDebugs here should be exported via displayErrors() so they
    // ### can be presented to the user if the job executor has a GUI
    QUrl requestedUrl = reply()->request().url();
    QUrl redirectUrl = reply()->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    if (!redirectUrl.isEmpty()) {
        _redirectCount++;
        if (requestedUrl.scheme() == QLatin1String("https") &&
                redirectUrl.scheme() == QLatin1String("http")) {
                qDebug() << Q_FUNC_INFO << "HTTPS->HTTP downgrade detected!";
        } else if (requestedUrl == redirectUrl || _redirectCount >= maxRedirects()) {
                qDebug() << Q_FUNC_INFO << "Redirect loop detected!";
        } else {
            resetTimeout();
            setReply(getRequest(redirectUrl));
            setupConnections(reply());
            return false;
        }
    }

    // The serverInstalls to /owncloud. Let's try that if the file wasn't found
    // at the original location
    if ((reply()->error() == QNetworkReply::ContentNotFoundError) && (!_subdirFallback)) {
        _subdirFallback = true;
        setPath(QLatin1String(owncloudDirC)+QLatin1String(statusphpC));
        start();
        qDebug() << "Retrying with" << reply()->url();
        return false;
    }

    bool success = false;
    QByteArray body = reply()->readAll();
    if( body.isEmpty() ) {
        emit instanceNotFound(reply());
    } else {
        QVariantMap status = QtJson::parse(QString::fromUtf8(body), success).toMap();
        // empty or invalid response
        if (!success || status.isEmpty()) {
            qDebug() << "status.php from server is not valid JSON!";
        }

        qDebug() << "status.php returns: " << status << " " << reply()->error() << " Reply: " << reply();
        if( status.contains("installed")
                && status.contains("version")
                && status.contains("versionstring") ) {
            emit instanceFound(reply()->url(), status);
        } else {
            qDebug() << "No proper answer on " << requestedUrl;
            emit instanceNotFound(reply());
        }
    }
    return true;
}
void vmsUrlMonRequestCollector::onInternetProtocolSink_ReportResult(IInternetProtocolSink *pSink, HRESULT hrResult, DWORD dwError, LPCWSTR szResult)
{
	vmsCriticalSectionAutoLock csal (&m_csReq);
	int nIndex = findRequestIndexBySink (pSink);
	ATLASSERT (nIndex != -1);
	if (nIndex == -1)
		return;
	Request *req = getRequest (nIndex);
	CloseRequest (req);
}
TEST_F(ProxygenTransportRepostTest, no_body) {
  InSequence enforceOrder;
  auto req = getRequest(HTTPMethod::POST);

  EXPECT_CALL(m_txn, sendHeaders(_));
  EXPECT_CALL(m_txn, sendEOM());
  m_transport->onHeadersComplete(std::move(req));
  m_transport->beginPartialPostEcho();
  m_transport->onEOM();
}