Esempio n. 1
0
void Pillow::HttpClient::device_connected()
{
	sendRequest();
}
Esempio n. 2
0
void MNMClass::requestSong(uint8_t _song) {
  sendRequest(MNM_SONG_REQUEST_ID, _song);
}
Esempio n. 3
0
// Send HTTP get and wait for response (SSL/SPP)
static int http_request(char *filename, char *proto, bool requestingFile, struct timeval *tvEnd){
	
	char buf[BUFSIZZ];
	int r;
	int len; 
	long bytes_read = 0;
    // Compute expected data size
	fSize = atoi(filename);
    if (fSize == 0 && filename[0] != '0'){
		if (requestingFile){
			fSize = calculate_file_size(filename);
		}else{
	    	fSize = strlen("HTTP/1.0 200 OK\r\n"); 
		}
	}   
	sizeCheck = fSize; 
	experiment_info->file_size = fSize;

	// Request file (either by name or by size) 
	if (requestingFile){
		sendRequest(filename); 
	}

	// Now read the server's response, assuming  that it's terminated by a close
	while(1){
		// SPP read
		if (strcmp(proto, "spp") == 0){
			/*
			#ifdef DEBUG
			printf("[DEBUG] SPP_read\n");
			#endif 
			*/
			SPP_SLICE *slice;		// slice for SPP_read
			SPP_CTX *ctx;			// context pointer for SPP_read
			r = SPP_read_record(ssl, buf, BUFSIZZ, &slice, &ctx);	
			#ifdef DEBUG 
			printf("[INFO] Read %d bytes\n", r);
			#endif
			if (ssl->read_stats.app_bytes == fSize){
				printf("[INFO] Read %d bytes as expected (fSize=%d). Stopping timer\n", ssl->read_stats.app_bytes, fSize);
				// Stop the timer here (avoid shutdown crap) 
				gettimeofday(tvEnd, NULL); 
				#ifdef VERBOSE
				fwrite(buf, 1, len, stdout);
				#endif
				break; 
				//goto shutdown;
			}
			switch(SSL_get_error(ssl, r)){
				case SSL_ERROR_NONE:
					len = r;
					break;

				case SSL_ERROR_ZERO_RETURN:
					goto shutdown;

				case SSL_ERROR_SYSCALL: 
					fprintf(stderr, "SSL Error: Premature close\n");
					goto done;

				default:
					berr_exit("SSL read problem");
			}
		} 
	
		// SSL read
		else if (strcmp(proto, "ssl") == 0){
			/*
			#ifdef DEBUG
			printf("[DEBUG] SSL_read\n");
			#endif 	
			*/
			r = SSL_read(ssl, buf, BUFSIZZ);
			#ifdef DEBUG 
			printf("[DEBUG] Read %d bytes\n", r);
			#endif
			if (ssl->read_stats.app_bytes == fSize){
				printf("[INFO] Read %d bytes as expected (fSize=%d). Stopping timer\n", ssl->read_stats.app_bytes, fSize);
				gettimeofday(tvEnd, NULL);
				// Write buf to stdout
				#ifdef VERBOSE
				fwrite(buf, 1, len, stdout);
				#endif
				break; 
			}
			switch(SSL_get_error(ssl, r)){
				case SSL_ERROR_NONE:
					len = r;
					break;

				case SSL_ERROR_ZERO_RETURN:
					goto shutdown;

				case SSL_ERROR_SYSCALL: 
					fprintf(stderr, "SSL Error: Premature close\n");
					goto done;

				default:
					berr_exit("SSL read problem");
			}
		}
		// SSL read
		else if (strcmp(proto, "pln") == 0){
			#ifdef DEBUG 
			printf("[DEBUG] Waiting to read bytes in plain mode\n");
			#endif
			r = read(plain_socket, buf, BUFSIZZ);
			experiment_info->app_bytes_read += r;
			bytes_read += r;
			#ifdef DEBUG 
			printf("[DEBUG] Read %d bytes\n", r);
			#endif
			if ( r <= 0 || bytes_read == fSize) /* done reading */
			{
				#ifdef DEBUG
				printf("[DEBUG] File transfer done, done reading socket...\n"); 
				#endif 
				gettimeofday(tvEnd, NULL);
				// Write buf to stdout
				#ifdef VERBOSE
				fwrite(buf, 1, len, stdout);
				#endif 
				goto done;
			}
		}
		
		// Write buf to stdout
		#ifdef VERBOSE
		fwrite(buf, 1, len, stdout);
		#endif 
    }
    
	shutdown:
		#ifdef DEBUG
		printf("[DEBUG] Shutdown was requested\n"); 
		#endif 
		r = SSL_shutdown(ssl);
		if( !r ){
			shutdown(SSL_get_fd(ssl), 1);
			r = SSL_shutdown(ssl);
		}

		switch(r){
			case 1:
				break; // Success 
			case 0:

			case -1:

			default:
				#ifdef DEBUG 
				printf ("Shutdown failed with code %d\n", r);
				#endif 
				berr_exit("Shutdown failed"); 
	}
    
	done:
		if (stats){
			print_stats(ssl);
		}
		SSL_free(ssl);
		return(0);
}
Esempio n. 4
0
void
LogFile::updateMonitor()
{
	sendRequest(sensors().at(0)->hostName(),
				QString("%1 %2" ).arg(sensors().at(0)->name()).arg(logFileID), 19);
}
Esempio n. 5
0
void MNMClass::requestKit(uint8_t _kit) {
  sendRequest(MNM_KIT_REQUEST_ID, _kit);
}
Esempio n. 6
0
int Video::upload_data(
        const uint64_t fileSize,
        const string &sha,
        const uint64_t sliceSize,
        const string &sign,
        const string &url,
        const string &srcPath,
        const uint64_t offset,
        const string &session
        ) {

    int ret = 0;
    char tmp_buf[1024];
    char buf[sliceSize];

    vector<string> headers;
    headers.push_back("Authorization: " + sign);

    ifstream fileInput(srcPath.c_str(),
            ios::in | ios::binary);

    fileInput.seekg(offset);

    uint64_t pos = offset;
    while (fileSize > pos) {
        reset();
        uint64_t len =0;
        fileInput.read(buf, sliceSize);
        len = fileInput.gcount();

        struct curl_httppost *firstitem = NULL,
                             *lastitem = NULL;

        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "op",
                CURLFORM_COPYCONTENTS, "upload_slice",
                CURLFORM_END);

        snprintf(tmp_buf, sizeof(tmp_buf), 
                "%lu", pos);
        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "offset",
                CURLFORM_COPYCONTENTS, tmp_buf,
                CURLFORM_END);

        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "session",
                CURLFORM_COPYCONTENTS, session.c_str(),
                CURLFORM_END);

        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "filecontent",
                CURLFORM_BUFFER, "data",
                CURLFORM_BUFFERPTR, buf,
                CURLFORM_BUFFERLENGTH, len,
                CURLFORM_END);

        int retry_times = 0;
        do {
            sendRequest(
                    url, 1, &headers, 
                    NULL, firstitem);
            dump_res();
            if (retCode == 0) {
                break;
            }
            retry_times++;
        } while(retry_times < MAX_RETRY_TIMES);

        curl_formfree(firstitem);

        if (retCode != 0) {
            return retCode;
        }

        pos += sliceSize;
    }

    return retCode;
}
Esempio n. 7
0
void HelpBrowser::gotoHelpFor( const QString & symbol )
{
    QString code = QString("HelpBrowser.openHelpFor(\"%1\")").arg(symbol);
    sendRequest(code);
}
Esempio n. 8
0
void SMTPConnection::authenticateSASL()
{
	if (!dynamicCast <security::sasl::SASLAuthenticator>(getAuthenticator()))
		throw exceptions::authentication_error("No SASL authenticator available.");

	// Obtain SASL mechanisms supported by server from ESMTP extensions
	std::vector <string> saslMechs;
	hasExtension("AUTH", &saslMechs);

	if (saslMechs.empty())
		throw exceptions::authentication_error("No SASL mechanism available.");

	std::vector <shared_ptr <security::sasl::SASLMechanism> > mechList;

	shared_ptr <security::sasl::SASLContext> saslContext =
		make_shared <security::sasl::SASLContext>();

	for (unsigned int i = 0 ; i < saslMechs.size() ; ++i)
	{
		try
		{
			mechList.push_back
				(saslContext->createMechanism(saslMechs[i]));
		}
		catch (const exceptions::no_such_mechanism&)
		{
			// Ignore mechanism
		}
	}

	if (mechList.empty())
		throw exceptions::authentication_error("No SASL mechanism available.");

	// Try to suggest a mechanism among all those supported
	shared_ptr <security::sasl::SASLMechanism> suggestedMech =
		saslContext->suggestMechanism(mechList);

	if (!suggestedMech)
		throw exceptions::authentication_error("Unable to suggest SASL mechanism.");

	// Allow application to choose which mechanisms to use
	mechList = dynamicCast <security::sasl::SASLAuthenticator>(getAuthenticator())->
		getAcceptableMechanisms(mechList, suggestedMech);

	if (mechList.empty())
		throw exceptions::authentication_error("No SASL mechanism available.");

	// Try each mechanism in the list in turn
	for (unsigned int i = 0 ; i < mechList.size() ; ++i)
	{
		shared_ptr <security::sasl::SASLMechanism> mech = mechList[i];

		shared_ptr <security::sasl::SASLSession> saslSession =
			saslContext->createSession("smtp", getAuthenticator(), mech);

		saslSession->init();

		if (saslSession->getMechanism()->hasInitialResponse())
		{
			byte_t* initialResp = 0;
			size_t initialRespLen = 0;

			saslSession->evaluateChallenge(NULL, 0, &initialResp, &initialRespLen);

			string encodedInitialResp(saslContext->encodeB64(initialResp, initialRespLen));
			delete [] initialResp;

			if (encodedInitialResp.empty())
				sendRequest(SMTPCommand::AUTH(mech->getName(), "="));
			else
				sendRequest(SMTPCommand::AUTH(mech->getName(), encodedInitialResp));
		}
		else
		{
			sendRequest(SMTPCommand::AUTH(mech->getName()));
		}

		for (bool cont = true ; cont ; )
		{
			shared_ptr <SMTPResponse> response = readResponse();

			switch (response->getCode())
			{
			case 235:
			{
				m_socket = saslSession->getSecuredSocket(m_socket);
				return;
			}
			case 334:
			{
				byte_t* challenge = nullptr;
				size_t challengeLen = 0;

				byte_t* resp = nullptr;
				size_t respLen = 0;

				try
				{
					// Extract challenge
					saslContext->decodeB64(response->getText(), &challenge, &challengeLen);

					// Prepare response
					saslSession->evaluateChallenge
						(challenge, challengeLen, &resp, &respLen);

					// Send response
					const string respB64 = saslContext->encodeB64(resp, respLen) + "\r\n";
					m_socket->sendRaw(utility::stringUtils::bytesFromString(respB64), respB64.length());

					if (m_tracer)
						m_tracer->traceSendBytes(respB64.length() - 2, "SASL exchange");
				}
				catch (const exceptions::sasl_exception& e)
				{
					delete [] challenge;
					challenge = nullptr;

					delete [] resp;
					resp = nullptr;
					
					// Cancel SASL exchange
					m_socket->send("*\r\n");

					if (m_tracer)
						m_tracer->traceSend("*");
				}
				catch (...)
				{
					delete [] challenge;
					delete [] resp;
					throw;
				}

				delete [] challenge;
				delete [] resp;

				break;
			}
			default:

				cont = false;
				break;
			}
		}
	}

	throw exceptions::authentication_error
		("Could not authenticate using SASL: all mechanisms failed.");
}
	lineEdit()->setStyleSheet(QLatin1String("QLineEdit {background:transparent;}"));
	lineEdit()->installEventFilter(this);

	ToolBarWidget *toolBar = qobject_cast<ToolBarWidget*>(parent);

	if (toolBar && toolBar->getIdentifier() != ToolBarsManager::NavigationBar)
	{
		connect(toolBar, SIGNAL(windowChanged(Window*)), this, SLOT(setWindow(Window*)));
	}

	connect(SearchesManager::getInstance(), SIGNAL(searchEnginesModified()), this, SLOT(storeCurrentSearchEngine()));
	connect(SearchesManager::getInstance(), SIGNAL(searchEnginesModelModified()), this, SLOT(restoreCurrentSearchEngine()));
	connect(SettingsManager::getInstance(), SIGNAL(valueChanged(QString,QVariant)), this, SLOT(optionChanged(QString,QVariant)));
	connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(currentIndexChanged(int)));
	connect(lineEdit(), SIGNAL(textChanged(QString)), this, SLOT(queryChanged(QString)));
	connect(m_completer, SIGNAL(activated(QString)), this, SLOT(sendRequest(QString)));

	setWindow(window);
}

void SearchWidget::changeEvent(QEvent *event)
{
	QComboBox::changeEvent(event);

	if (event->type() == QEvent::LanguageChange && itemData(currentIndex(), Qt::AccessibleDescriptionRole).toString().isEmpty())
	{
		lineEdit()->setPlaceholderText(tr("Search using %1").arg(currentData(Qt::UserRole).toString()));
	}
}

void SearchWidget::paintEvent(QPaintEvent *event)
Esempio n. 10
0
Bool TERMWINDOWMEMBER dc15network(Bool master)
	{
	char line[100], line2[100];
	label here, there;
	FILE *file;
	int i, rms;
	Bool done = FALSE;

	netFailed = FALSE;

	const protocols *theProt = GetProtocolByKey(node->GetProtocol(), TRUE);

	if (!theProt)
		{
		doccr();
		cPrintf(getnetmsg(177));
		doCR();
		return (FALSE);
		}

	if (!CommPort->HaveConnection())
		{
		return (FALSE);
		}

	sprintf(line, sbs, LocalTempPath, mesgTmp);
	unlink(line);

	sprintf(line, getnetmsg(123), LocalTempPath);
	unlink(line);

	sprintf(line, getnetmsg(124), LocalTempPath);
	unlink(line);

	sprintf(line, getnetmsg(125), LocalTempPath);
	unlink(line);

	if ((file = fopen(line, FO_AB)) == NULL)
		{
		perror(getnetmsg(25));
		return (FALSE);
		}

	for (i = get_first_room(here, there), rms = 0; i; i = get_next_room(here, there), rms++)
		{
		PutStr(file, there);
		}

	PutStr(file, ns);
	fclose(file);

	if (master)
		{
		sendRequest(theProt);
		if (!CommPort->HaveConnection())
			{
			return (FALSE);
			}

		reciveRequest(theProt);
		}
	else
		{
		reciveRequest(theProt);
		if (!CommPort->HaveConnection())
			{
			return (FALSE);
			}

		sendRequest(theProt);
		}

	if (!CommPort->HaveConnection() || netFailed)
		{
		return (FALSE);
		}

	if (master)
		{
		// clear the buffer
		while (CommPort->HaveConnection() && CommPort->IsInputReady())
			{
			CommPort->Input();
			}
		}

	makeSendFile();

	if (!CommPort->HaveConnection() || netFailed)
		{
		return (FALSE);
		}

	// wait for them to get their shit together
	cPrintf(getnetmsg(11));

	CommPort->Output('X');

	time_t t2 = 0;
	const time_t t = time(NULL);

	while (CommPort->HaveConnection() && !done)
		{
		if (time(NULL) > (t + (node->GetFetchTimeout() * 60)))
			{
			CITWINDOW *w = ScreenSaver.IsOn() ? NULL : CitWindowsMsg(NULL, getmsg(685), getmsg(73));

			Hangup();
			netFailed = TRUE;

			if (w)
				{
				destroyCitWindow(w, FALSE);
				}
			}

		KBReady();

		if (CommPort->IsInputReady())
			{
			i = CommPort->Input();
			if (i == 'X' || node->GetNetworkType() != NET_DCIT16)
				{
				done = TRUE;
				}
			else
				{
				DebugOut(pctc, i);
				}

			}

		// wake them up! (every second)
		if (time(NULL) != t2)
			{
			CommPort->Output('X');
			t2 = time(NULL);
			}

		// instantaneous reaction time isn't critical here
		CitIsIdle();
		}

	// wake them up!
	for (i = 0; i < 10; i++)
		{
		CommPort->Output('X');
		}

	doccr();

	if (!CommPort->HaveConnection() || netFailed)
		{
		return (FALSE);
		}

	if (master)
		{
		receiveFiles(theProt);
		if (!CommPort->HaveConnection() || netFailed)
			{
			return (FALSE);
			}

		sendFiles(theProt);
		}
	else
		{
		sendFiles(theProt);
		if (!CommPort->HaveConnection() || netFailed)
			{
			return (FALSE);
			}

		receiveFiles(theProt);
		}

	if (netFailed)
		{
		return (FALSE);
		}

	cPrintf(getnetmsg(84));
	doccr();

	CITWINDOW *w = ScreenSaver.IsOn() ? NULL : CitWindowsMsg(NULL, getmsg(82));

	Hangup();

	if (w)
		{
		destroyCitWindow(w, FALSE);
		}

	OC.setio(); // hmmm

	cPrintf(getnetmsg(85), cfg.Lmsg_nym);
	doccr();

	sformat(line, node->GetExtractPacket(), getmsg(48), roomdataIn, 0);
	apsystem(line, TRUE);

	changedir(LocalTempPath);
	unlink(roomdataIn);

	for (i = 0; i < rms; i++)
		{
		sprintf(line, getnetmsg(126), i);
		sprintf(line2, getnetmsg(127), i);
		rename(line, line2);
		}

	sprintf(line, sbs, LocalTempPath, mesgTmp);
	sprintf(line2, getnetmsg(123), LocalTempPath);
	rename(line, line2);

	return (TRUE);
	}
Esempio n. 11
0
/**
 * Handle client communications
 */
void client_task_impl() {

	uip_tcp_appstate_t *app = &(uip_conn->appstate);
	GETrequest *req = (GETrequest*)app->request;

	if (uip_connected()) {

		if (verbose) {
			Serial.print("Connected to ");
			Serial.println(req->hostName);
		}
		app->ackedCount = 0;
		sendRequest();
	}

	// Did we get an ack for the last packet?
	if (uip_acked()) {
		// Record the bytes that were successfully sent
		app->ackedCount += app->sentCount;
		app->sentCount = 0;

		// Check if we're done or need to send more content for this
		// request
		if (app->ackedCount != (int)app->cursor) {
			// Generate the post again to send the next packet of data
			sendRequest();
		}
	}

	if (uip_rexmit()) {
		sendRequest();
	}

 	if (uip_newdata())  {
 		setRXPin(HIGH);

		if (verbose) {
			Serial.print("RX ");
			Serial.print(uip_datalen());
			Serial.print(" bytes from ");
			Serial.println(req->hostName);
		}

		// Check if the sketch cares about the returned data
	 	if ((req->returnFunc) && (uip_datalen() > 0)){
			// Call the sketch's callback function
	 		req->returnFunc((char*)uip_appdata, uip_datalen());
	 	}
 	}

	if (uip_aborted() || uip_timedout() || uip_closed()) {
		if (req != NULL) {
			if (verbose) {
				Serial.print("Ended connection with ");
				Serial.println(req->hostName);
			}

			if (req->returnFunc) {
				// Call the sketch's callback function with 0 bytes to indicate End Of Data
				req->returnFunc((char*)uip_appdata, 0);
			}
			// Remove the request from the connection
			app->request = NULL;
			// Request is no longer active
			req->active = false;
		}
	}
}
void YahooFinanceNetworkRequest::handleReply(QNetworkReply *pReply)
{
    if (!pReply)
    {
        qDebug() << "YahooFinanceNetworkRequest::handleReply, null handle, ignored";
        return;
    }

    if (pReply == mpNetworkReply.data())
    {
        qDebug() << "YahooFinanceNetworkRequest::handleReply, reply belongs to us, parsing data...";
        const QVariant http_status_code = pReply->attribute(
                    QNetworkRequest::HttpStatusCodeAttribute);
        bool is_error = pReply->error() != QNetworkReply::NoError;

        qDebug() << "YahooFinanceNetworkRequest::handleReply, HTTP status:"
                 << http_status_code.toString()
                 << ", is error:" << is_error;
        if (!is_error && HTTP_REPLY_CODE_OK == http_status_code.toInt())
        {
            int line_index = 0;
            while (pReply->canReadLine() && mTickers.count() > line_index)
            {
                const QString line(pReply->readLine());
                const QString ticker = mTickers.at(line_index);
                const QStringList data = line.simplified().split(",");
                if (mParameters.count() == data.count())
                {
                    QMap<YahooFinance::StockParameter, QString> data_mappings;
                    for (int value_index = 0; value_index < data.count(); value_index++)
                    {
                        const YahooFinance::StockParameter param = mParameters.at(value_index);
                        const QString value = data.at(value_index);
                        qDebug() << "ticker:" << ticker << ", param:" << param << ", value:" << value;
                        data_mappings.insert(param, value);
                    }

                    emit parametersReceived(mQueryIdentifier, ticker, data_mappings);
                }
                else
                {
                    handleError();
                }
                line_index++;
            }
        }
        else if (HTTP_REPLY_MOVED_PERMANENTLY == http_status_code)
        {
            const QVariant redirection_url = pReply->attribute(
                        QNetworkRequest::RedirectionTargetAttribute);
            qDebug() << "Moved permanently, url:" << redirection_url;
            mUrl.setUrl(redirection_url.toString());
            sendRequest();
        }
        else
        {
            handleError();
            qDebug() << "YahooFinanceNetworkRequest::handleReply, ERROR";
        }

        mpNetworkReply.reset();
    }
    else
    {
        qDebug() << "YahooFinanceNetworkRequest::handleReply, unknown handle, not handled";
        pReply->deleteLater();
    }
}
Esempio n. 13
0
am_status_t
BaseService::doRequest(const ServiceInfo& service,
        const BodyChunk& headerPrefix,
        const std::string& uriParameters,
        const Http::CookieList& cookieList,
        const BodyChunk& headerSuffix,
        const BodyChunkList& bodyChunkList,
        Http::Response& response,
        const ServerInfo** serverInfo) const {
    am_status_t status = AM_SERVICE_NOT_AVAILABLE;
    int dataLen = 0;
    BodyChunk emptyContentLine;
    // Create a temporary buffer for the Content-Line header
    // the extra '2' is for the <CR><LF> at the end.  The
    // sizeof the CONTENT_LENGTH_HDR includes space for the
    // terminating NUL.
    const std::size_t contentLineLen_sz = sizeof (CONTENT_LENGTH_HDR) +
            (sizeof (dataLen) * DIGITS_PER_BYTE) + 2;
    char contentLine[contentLineLen_sz + 1];
    std::size_t contentLineLen = 0;

    for (unsigned int i = 0; i < bodyChunkList.size(); ++i) {
        dataLen += bodyChunkList[i].data.size();
    }

    memset(&contentLine[0], 0, contentLineLen_sz);
    contentLineLen = snprintf(contentLine, contentLineLen_sz, "%s%d\r\n",
            CONTENT_LENGTH_HDR, dataLen);

    if (contentLineLen_sz > contentLineLen && contentLineLen > 0) {
        BodyChunk contentLineChunk(contentLine, contentLineLen);
        ServiceInfo::const_iterator iter;
        ServiceInfo svc(service);
        int j = -1, current_index = -1;
        if (am_web_naming_validation_status() < 2 && svc.getNumberOfServers() > 1) {
            /* validation is enabled and number of servers is more than one */
            char *current_value = read_naming_value(AM_NAMING_LOCK, Log::getLockId());
            if (current_value != NULL) {
                current_index = strtol(current_value, NULL, 10);
                if (current_index < 0 || errno == ERANGE) {
                    current_index = 0;
                } else {
                    Log::log(logModule, Log::LOG_MAX_DEBUG,
                            "BaseService::doRequest(): will be using url index: %d",
                            current_index);
                }
                free(current_value);
            } else {
                current_index = 0;
            }
            if ((size_t) current_index >= svc.getNumberOfServers()) {
                Log::log(logModule, Log::LOG_WARNING,
                        "BaseService::doRequest(): invalid url index: %d (out of %d); validation results ignored.",
                        current_index, svc.getNumberOfServers());
                current_index = -1;
            }
        }

        for (iter = svc.begin(); iter != svc.end(); ++iter) {
            const ServerInfo &svrInfo = (*iter);

            if (current_index != -1) {
                if ((++j) != current_index) {
                    Log::log(logModule, Log::LOG_MAX_DEBUG,
                            "BaseService::doRequest(): skipping url(%d) %s",
                            j, svrInfo.getURL().c_str());
                    continue;
                } else {
                    Log::log(logModule, Log::LOG_MAX_DEBUG,
                            "BaseService::doRequest(): using url(%d) %s",
                            j, svrInfo.getURL().c_str());
                }
            }

            Http::HeaderList headerList, proxyHeaderList;
            Http::Cookie hostHeader("Host", svrInfo.getHost());
            headerList.push_back(hostHeader);

#ifdef AGENT_PROXY_SUPPORT
#ifndef _MSC_VER
            if (useProxy) {
                proxyHeaderList.push_back(hostHeader);
                // Override (temporarily) server credentials if using proxy
                //svrInfo.setHost(proxyHost);
                //svrInfo.setPort(proxyPort);
                // We don't use SSL for initial proxy connection
                //svrInfo.setUseSSL(false);
                Log::log(logModule, Log::LOG_DEBUG,
                        "BaseService::doRequest(): Using proxy: %s:%d",
                        proxyHost.c_str(), proxyPort);
                // Add Proxy-Authorization header if user defined
                if (useProxyAuth) {
                    // allocate enough for a base64-encoded digest
                    size_t authSize = proxyUser.size() +
                            proxyPassword.size() + 1;
                    // 11 extra bytes for prefix and terminator
                    char * digest = (char *) malloc(authSize * 4 / 3 + 11);
                    strcpy(digest, "Basic ");
                    encode_base64((proxyUser + ":" + proxyPassword).c_str(),
                            authSize, (digest + 6));
                    Log::log(logModule, Log::LOG_MAX_DEBUG,
                            "BaseService::doRequest(): Using proxy auth as: %s",
                            proxyUser.c_str());
                    hostHeader = Http::Cookie("Proxy-Authorization", digest);
                    proxyHeaderList.push_back(hostHeader);
                    free(digest);
                }
            }
#endif
#endif

            // retry to connect to server before marking it as down.
            // making the number of attempts configurable may have a negative
            // side effect on performance, if the the value is a high number.
            int retryAttempts = 3;
            int retryCount = 0;
            while (retryCount < retryAttempts) {
                retryCount++;
                try {
                    const char *operation = "sending to";
                    Connection conn(svrInfo.getHost().c_str(), svrInfo.getPort(), svrInfo.useSSL());
#ifdef AGENT_PROXY_SUPPORT
                    std::string requestString = svrInfo.getURI().c_str();
                    /*
                     * In case the following request would go to a proxy
                     * we need to use full URL and special headers.
                     */

                    if (useProxy && !(iter->useSSL())) {
                       requestString = iter->getURL();
                       headerList = proxyHeaderList;
                    }
#endif
                    status = sendRequest(conn, headerPrefix, svrInfo.getURI(),
                            uriParameters, headerList, cookieList,
                            dataLen > 0 ? contentLineChunk : emptyContentLine, headerSuffix,
                            bodyChunkList);
                    if (AM_SUCCESS == status) {
                        operation = "receiving from";
                        status = response.readAndParse(logModule, conn);
                        if (AM_SUCCESS == status) {
                            Log::log(logModule, Log::LOG_MAX_DEBUG, "Response::readAndParse() (%d) %s",
                                    response.getBodyLen(), response.getBodyPtr() ? response.getBodyPtr() : "(NULL)");
                        }
                    }

                    if (AM_NSPR_ERROR == status) {
                        Log::log(logModule, Log::LOG_ALWAYS,
                                "BaseService::doRequest() NSPR failure while "
                                "%s %s", operation,
                                svrInfo.getURL().c_str());
                    }

                    if (AM_SUCCESS == status) {
                        break;
                    } else {
                        if (retryCount < retryAttempts) {
                            continue;
                        } else {
                            Log::log(logModule, Log::LOG_DEBUG,
                                    "BaseService::doRequest() Invoking markSeverDown");
                            /*svrInfo.markServerDown(poll_primary_server);*/
                        }
                    }
                } catch (const NSPRException& exc) {
                    Log::log(logModule, Log::LOG_ERROR,
                            "BaseService::doRequest() caught %s: %s called by %s", exc.what(), exc.getNsprMethod(),
                            exc.getThrowingMethod());

                    if (retryCount < retryAttempts) {
                        status = AM_NSPR_ERROR;
                        continue;
                    } else {
                        Log::log(logModule, Log::LOG_ERROR,
                                "BaseService::doRequest() Invoking markSeverDown");
                        /*svrInfo.markServerDown(poll_primary_server);*/
                        status = AM_NSPR_ERROR;
                    }
                }
            } //end of while

            if (AM_SUCCESS == status) {
                break;
            }

        } // end of for
    } else {
        status = AM_BUFFER_TOO_SMALL;
    }

    return status;
}
Esempio n. 14
0
int main(int argc, char * argv[]) {
  //check comand line paremeters
  if (argc < 10) {
	  printf("usage: client ip port requestfilename requestNum cancelOrStop(1 is cancel, 0 is stop) netinterface filterExpression serverbandstatus sleepTime\n");
	  return 1;
  }
  // check cancel parameter
  int isCancel = 0;
  char *prefix = argv[8];
  int sleepTime = atoi(argv[9]);
  if (strcmp(argv[5], "1") == 0) {
	isCancel = 1;
  }
  //init logFile
  char logFile[FILE_NAME_SIZE] = {0};
  if (initLogFile(logFile, sizeof logFile -1, isCancel, prefix) != 0) {
	fprintf(stderr, "init logfile failed\n");
	return 1;
  }
  printf("isCancel:%d\n", isCancel);
  printf("log file name is %s\n", logFile);
  struct ClientSockInfo sockInfo;
  if (initClientSockInfo(&sockInfo, argv[1], argv[2]) == 0) {
	printf("init client sockinfo successfully\n");
  } else {
	fprintf(stderr, "init client sockinfo failed\n");
	return 1;
  }
  char * requestFileName = argv[3];
  int requestNum = atoi(argv[4]);
  //init sniffPanel
  struct SniffPanel sniffPanel;
  sniffPanel.device = argv[6];
  sniffPanel.filterExpression = argv[7];
  sniffPanel.liveReadTimeOut = 2000;//default 2000 ms
  sniffPanel.payloadFilePath = NULL;
  sniffPanel.payloadFile = NULL;
  sniffPanel.cbAfterSniff = &cbAfterSniff;
  sniffPanel.cbWhenError  = &cbForSniffError;
  sniffPanel.cbLog        = &cbForSniffLog;
  sniffPanel.afterSniffArgs = (void *)logFile;
  sniffPanel.errorArgs      = NULL;
  sniffPanel.isStopped      = 1;
  if (initSniff(&sniffPanel) != 0) {
	fprintf(stderr, "init packet sniff error\n");
	return 1;
  } else {
	printf("finish initializing packet sniff\n");
  }
  pthread_t sniffThread;
  int i = 0;
  while (i < requestNum) {
	if (!sniffPanel.isStopped) {
	  printf("we need to stop the last sniff before starting new round\n");
	  if (stopSniff(&sniffPanel) != 0) {
		fprintf(stderr, "stop sniff failed\n");
		continue;
	  } else {
		printf("finish stopping the last sniff before starting new round\n");
	  }
	}
	i++;
    printf("round %d\n", i);
	//create connection to server
	//if (i == 1 || !isCancel) {
	//  if (createNewConn(&sockInfo) != 0) {
	//	fprintf(stderr, "create new connection failed \n");
	//	return 1;
	//  } else {
	//	printf("connect to server %s:%d successfully from port %d\n", sockInfo.serverIpStr, sockInfo.serverPort, sockInfo.clientPort);
	//  }
	//}
	if (createNewConn(&sockInfo) != 0) {
      i--;
	  fprintf(stderr, "create new connection failed \n");
      continue;
	} else {
	  printf("connect to server %s:%d successfully from port %d\n", sockInfo.serverIpStr, sockInfo.serverPort, sockInfo.clientPort);
	}

	//configure packet sniff and start thread
	sniffPanel.packetNum      = 0;
	sniffPanel.payloadSize    = 0;
	sniffPanel.isStopped      = 0;
	pthread_create(&sniffThread, NULL, sniffThreadFunc, (void *)&sniffPanel);

	printf("finish starting thread for sniff\n");
	//send request
	if (sendRequest(&sockInfo, requestFileName, strlen(requestFileName)) == 0) {
	  printf("send request successfully\n");
	} else {
	  fprintf(stderr, "send request failed\n");
	  shutdown(sockInfo.clientSockFd, SHUT_RDWR);
      i--;
      continue;
	}

	//receive response within random time
	int randomSecs = generateRandom(RANDOM_RANGE);
	randomSecs += 10;
	sockInfo.recvedBytes = 0;
	printf("start to recv within %d seconds\n", randomSecs);
	if (recvWithInRandom(&sockInfo, randomSecs) == 0) {
	  printf("recv %d KB in %d seconds\n", sockInfo.recvedBytes / 1024, randomSecs);
	} else {
	  fprintf(stderr, "recv failed in round %d with random %d\n", i, randomSecs);
	  shutdown(sockInfo.clientSockFd, SHUT_RDWR);
      i--;
      continue;
	}


	//send cancel or close signal
	const char *signal = isCancel? STOP_MSG : CLOSE_MSG;
	if (sendRequest(&sockInfo, signal, strlen(signal)) == 0) {
	  printf("finish sending signal : %s\n", signal);
	} else {
	  fprintf(stderr, "failed to send signal\n");
	  shutdown(sockInfo.clientSockFd, SHUT_RDWR);
      i--;
      continue;
	}

	//decide whether to close sock immediately after sending out cancel signal
	if (!isCancel) {
	  printf("shutdown for close test\n");
	  closeSock(sockInfo.clientSockFd);
	  printf("sleep for %d seconds in close test\n", sleepTime);
	  sleep(sleepTime);
	} else {
	  printf("continue receive for cancel test\n");
	  struct timeval timeout;
	  timeout.tv_sec = 5;
	  timeout.tv_usec = 0;
	  int recvAfterCancel = receiveFromSockUtilTimeout(sockInfo.clientSockFd, &timeout);
	  printf("recv %d KB after sending cancel signal", recvAfterCancel / 1024);
	  printf("shutdown connection for cancel test\n");
	  closeSock(sockInfo.clientSockFd);
	}

	//record log
	if (appendLog(logFile, &sockInfo, randomSecs) == 0) {
	  printf("finish appending new log\n");
	} else {
	  fprintf(stderr, "failed to append new log\n");
      i--;
      continue;
	}
	if (stopSniff(&sniffPanel) != 0) {
	  fprintf(stderr, "stop sniff failed\n");
      i--;
      continue;
	} else {
	  printf("finish stopping sniff with packets: %d, payloadSize: %d\n", sniffPanel.packetNum, sniffPanel.payloadSize / 1024);
	}
  }
}
Esempio n. 15
0
int Video::upload(
        const string &srcPath,
        const string &bucketName,
        const string &dstPath,
        const string &videoCover,
        const string &bizAttr,
		const string &title,
		const string &desc,
		const string &magicContext) {

    reset();
    int ret = 0;
    ret = access(srcPath.c_str(), F_OK | R_OK);
    if (ret != 0) {
        retCode = VIDEO_FILE_NOT_EXISTS;
        retMsg = "file not exist or can not be read...";
        return retCode;
    }

    string encodePath = videoUrlEncode(dstPath);
    uint64_t expired = time(NULL) + EXPIRED_SECONDS;
    string url = generateResUrl(bucketName, encodePath);

    string sign =
        Auth::appSign(
                APPID, SECRET_ID, SECRET_KEY,
                expired, bucketName);

    vector<string> headers;
    headers.push_back("Authorization: " + sign);

    string sha1 = genFileSHA1AndLen(srcPath);

    struct curl_httppost *firstitem = NULL,
                         *lastitem = NULL;

    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "op",
            CURLFORM_COPYCONTENTS, "upload",
            CURLFORM_END);

    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "sha",
            CURLFORM_COPYCONTENTS, sha1.c_str(),
            CURLFORM_END);

    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "video_cover",
            CURLFORM_COPYCONTENTS, videoCover.c_str(),
            CURLFORM_END);
            
    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "biz_attr",
            CURLFORM_COPYCONTENTS, bizAttr.c_str(),
            CURLFORM_END);

    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "video_title",
            CURLFORM_COPYCONTENTS, title.c_str(),
            CURLFORM_END);

    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "video_desc",
            CURLFORM_COPYCONTENTS, desc.c_str(),
            CURLFORM_END);

    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "magicContext",
            CURLFORM_COPYCONTENTS, magicContext.c_str(),
            CURLFORM_END);
			
    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "filecontent",
            CURLFORM_FILE, srcPath.c_str(),
            CURLFORM_END);

    sendRequest(url, 1, &headers, NULL, firstitem);
    curl_formfree(firstitem);
    return retCode;
}
Esempio n. 16
0
    /*------------------------------------------------------------------------------*

     *------------------------------------------------------------------------------*/
    void WebProxy::processQuery() {
        QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
        QByteArray requestData = socket->readAll();

        int pos = requestData.indexOf("\r\n");
        QByteArray requestLine = requestData.left(pos);
        requestData.remove(0, pos + 2);

        QList<QByteArray> entries = requestLine.split(' ');
        QByteArray method = entries.value(0);
        QByteArray address = entries.value(1);
        QByteArray version = entries.value(2);

        qDebug( )  << __FILE__ << __FUNCTION__ << "Processing " << address;

        QUrl url = QUrl::fromEncoded(address);
        if (!url.isValid()) {
            //qWarning() << "Invalid URL:" << url;
            socket->disconnectFromHost();
            return;
        }

        //Act as server is request are for local server
        if ((url.host() == "") && (QFile(address).exists())) {
            //qDebug( )  << __FILE__ << __FUNCTION__ << "Sending " << address;
            QByteArray header;
            QTextStream headerStream(&header, QIODevice::WriteOnly);
            //Construct response header
            headerStream << "HTTP/1.0 200 OK" << endl;
            headerStream << "Server: gpsbook/" << qApp->applicationVersion() << endl;
            headerStream << "Date: " << QDateTime::currentDateTime().toUTC().toString("ddd, dd MMM yyyy hh:mm:ss") << "GMT" << endl;
            headerStream << "Content-Type: text/html; charset=utf-8" << endl;
            headerStream << "Connection: close" << endl;
            headerStream << "Pragma: no-cache" << endl;
            headerStream << "Cache-Control: no-cache" << endl;
            QFile file(address);
            if (!file.open(QFile::ReadOnly | QFile::Text))
            {
                 qWarning() << "Cannot open:" << address;
                 socket->disconnectFromHost();
                 return ;
            }

            QByteArray content;
            QTextStream contentStream(&content, QIODevice::WriteOnly);

            while (!file.atEnd()) {
                contentStream << file.readLine() << endl;
            }

            headerStream << "Content-Length:" << content.size() << endl;
            headerStream << "" << endl;

            socket->write(header);
            socket->write(content);
            //qDebug( )  << __FILE__ << __FUNCTION__ << "File sent (" << content.size() << "bytes) :-)";
            socket->disconnectFromHost();
        return;
        }


#if ( QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) )
        // Some finction of QUrl have been deprecated
        // This code is require for the internet browser and should be reviewed.
#else


#ifdef Q_OS_LINUX
        //Remove advert to speedup development ;-)
        if (url.toString().contains("googlesyndication") ||
            url.toString().contains("yieldmanager.com")) {
            socket->disconnectFromHost();
            return;
        }
#endif

        qDebug( )  << __FILE__ << __FUNCTION__ << "URL: " << url.toString();

        QString host = url.host();
        int port = (url.port() < 0) ? 80 : url.port();
        QByteArray req = url.encodedPath();
        if (url.hasQuery())
            req.append('?').append(url.encodedQuery());
        requestLine = method + " " + req + " " + version + "\r\n";
        requestData.prepend(requestLine);

        QString key = host + ':' + QString::number(port);
        QTcpSocket *proxySocket = socket->findChild<QTcpSocket*>(key);
        if (proxySocket) {
            proxySocket->setObjectName(key);
            proxySocket->setProperty("url", url);
            proxySocket->setProperty("requestData", requestData);
            proxySocket->write(requestData);
        } else {
            proxySocket = new QTcpSocket(socket);
            proxySocket->setObjectName(key);
            proxySocket->setProperty("url", url);
            proxySocket->setProperty("requestData", requestData);
            connect(proxySocket, SIGNAL(connected()), this, SLOT(sendRequest()));
            connect(proxySocket, SIGNAL(readyRead()), this, SLOT(transferData()));
            connect(proxySocket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
            connect(proxySocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(closeConnection()));
            proxySocket->connectToHost(host, port);
        }
#endif
    } //WebProxy::processQuery
Esempio n. 17
0
int Video::upload_prepare(
        const uint64_t fileSize,
        const string &sha,
        const string &sign,
        const string &url,
        const string &videoCover,
        const string &bizAttr,
		const string &title,
		const string &desc,
		const string &magicContext,
        const string &session,
        const uint64_t sliceSize
        ) {
    reset();

    int ret = 0;
    char buf[1024];
    struct curl_httppost *firstitem = NULL,
                         *lastitem = NULL;

    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "op",
            CURLFORM_COPYCONTENTS, "upload_slice",
            CURLFORM_END);

    snprintf(buf, sizeof(buf), "%lu", fileSize);
    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "filesize",
            CURLFORM_COPYCONTENTS, buf,
            CURLFORM_END);

    ret = curl_formadd(&firstitem, &lastitem,
            CURLFORM_COPYNAME, "sha",
            CURLFORM_COPYCONTENTS, sha.c_str(),
            CURLFORM_END);

    if (!videoCover.empty()) {
        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "video_cover",
                CURLFORM_COPYCONTENTS, videoCover.c_str(),
                CURLFORM_END);
    }   
            
    if (!bizAttr.empty()) {
        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "biz_attr",
                CURLFORM_COPYCONTENTS, bizAttr.c_str(),
                CURLFORM_END);
    }

    if (!title.empty()) {
		ret = curl_formadd(&firstitem, &lastitem,
				CURLFORM_COPYNAME, "video_title",
				CURLFORM_COPYCONTENTS, title.c_str(),
				CURLFORM_END);
	}
	
	if (!desc.empty()) {
		ret = curl_formadd(&firstitem, &lastitem,
				CURLFORM_COPYNAME, "video_desc",
				CURLFORM_COPYCONTENTS, desc.c_str(),
				CURLFORM_END);
	}		
			
    if (!magicContext.empty()) {
		ret = curl_formadd(&firstitem, &lastitem,
				CURLFORM_COPYNAME, "magicContext",
				CURLFORM_COPYCONTENTS, magicContext.c_str(),
				CURLFORM_END);
	}
	
    if (!session.empty()) {
        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "session",
                CURLFORM_COPYCONTENTS, session.c_str(),
                CURLFORM_END);
    }

    if (sliceSize > 0) {
        if (sliceSize <= DEFAULT_SLICE_SIZE) {
            snprintf(
                buf, sizeof(buf), "%lu", sliceSize);
        } else {
            snprintf(
                buf, sizeof(buf), "%lu", sliceSize);
        }

        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "slice_size",
                CURLFORM_COPYCONTENTS, buf,
                CURLFORM_END);
    }

    vector<string> headers;
    headers.push_back("Authorization: " + sign);

    sendRequest(url, 1, &headers, NULL, firstitem);
    curl_formfree(firstitem);
    return retCode;
}
Esempio n. 18
0
/**
 * send a GET request
 * @return http code
 */
int HTTPClient::GET() {
    return sendRequest("GET");
}
Esempio n. 19
0
void HelpBrowser::goHome()
{
    static QString code( "HelpBrowser.goHome" );
    sendRequest(code);
}
Esempio n. 20
0
/**
 * sends a post request to the server
 * @param payload uint8_t *
 * @param size size_t
 * @return http code
 */
int HTTPClient::POST(uint8_t * payload, size_t size) {
    return sendRequest("POST", payload, size);
}
Esempio n. 21
0
void HelpBrowser::gotoHelpForMethod( const QString & className, const QString & methodName )
{
    QString code = QString("HelpBrowser.openHelpForMethod( %1.findMethod(\\%2) )").arg(className, methodName);
    sendRequest(code);
}
Esempio n. 22
0
void UpdateChecker::start() {
	sendRequest();
}
Esempio n. 23
0
LogFile::~LogFile(void)
{
	sendRequest(sensors().at(0)->hostName(), QString("logfile_unregister %1" ).arg(logFileID), 43);
}
Esempio n. 24
0
bool HttpAgent::async(const QObject * receiver, const char * method,
	const QString& httpMethod, const Route& route, const QMap<QString, QVariant>& params,
	const QMap<QString, QString>& filePaths,
	const QMap<QString, QVariant>& argsToSlot,
	const QObject * downloadProgressReceiver, const char * downloadProgressMethod
)
{
	//在路由里取出url规则
	QString routePattern = route.pattern();
qDebug() << "Services::async():" << routePattern;

	//遍历所有"默认参数"(如:_format, _locale), 做替换
	QMapIterator<QString, QVariant> defaultParamIterator(defaultParams);
	while ( defaultParamIterator.hasNext() )
	{
		defaultParamIterator.next();
		QString toReplace = QString("{") + defaultParamIterator.key() + QString("}");
		routePattern.replace( toReplace, defaultParamIterator.value().toString() );
qDebug() << "Services::async():replace("<< defaultParamIterator.key() << "," << defaultParamIterator.value() << "):" << routePattern;
	}
qDebug() << "Services::async():" << routePattern;


	//QString paramsString;
	QUrlQuery query;
	int paramCount = 0;
	QMapIterator<QString, QVariant> i(params);
	while ( i.hasNext() )
	{
		i.next();

		/*if ( paramCount > 0 )
		{
			paramsString += "&";
		}
		paramsString += i.key();
		paramsString += '=';
		paramsString += i.value();*/
		QString value = QString( QUrl::toPercentEncoding( i.value().toString(), "", "+" ) );

		query.addQueryItem(i.key(), value);

		//replace if found in urlPattern
		QString toReplace = QString("{") + i.key() + QString("}");
		routePattern.replace( toReplace, i.value().toString() );

		paramCount++;
	}

	/*QString paramString = query.query(QUrl::FullyEncoded);
	QByteArray ba = QUrl::toPercentEncoding(paramString, "&=", "+");
	qDebug() << "BA ==== " << ba;*/

qDebug() << "Services::async(): paramsString: \"" << query.query(QUrl::FullyEncoded) << "\""; //paramsString << "\"";

	QString host = !route.host().isEmpty() ? route.host() : defaultHost;
	QString url(defaultProtocol + "://" + host + routePattern);

	//req.setRawHeader(QByteArray("X-Requested-With"), QByteArray("XMLHttpRequest"));
	QMap<QString, QString> headers;
	headers[ "X-Requested-With" ] = "XMLHttpRequest";

	return sendRequest(httpMethod,
		url,
		params, //query.query(QUrl::FullyEncoded), //paramsString, //"email="+loginName+"&password="+password,
		filePaths,
		headers,
		receiver, method, argsToSlot, downloadProgressReceiver, downloadProgressMethod );

}
Esempio n. 25
0
void MNMClass::requestPattern(uint8_t _pattern) {
  sendRequest(MNM_PATTERN_REQUEST_ID, _pattern);
}
void
ClientHandler::check_create_pipeline_call()
{
  Json::Value request;
  Json::Value response;
  std::string pipeId;
  std::string objId;

  Json::Value params;
  Json::Value constructorParams;
  Json::Value operationParams;

  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "create";

  params["type"] = "MediaPipeline";
  params["sessionId"] = "123456";

  request["params"] = params;
  request["sessionId"] = "sessionId";

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("value") );
  BOOST_CHECK (response["result"]["value"].isString() );

  pipeId = response["result"]["value"].asString();

  params["type"] = "WebRtcEndpoint";
  constructorParams ["mediaPipeline"] = pipeId;
  params["constructorParams"] = constructorParams;
  params["sessionId"] = "123456";

  request["id"] = getId();
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("value") );
  BOOST_CHECK (response["result"]["value"].isString() );

  objId = response["result"]["value"].asString();

  request["method"] = "invoke";
  params.clear();
  params["object"] = objId;
  params["operation"] = "getName";
  params["sessionId"] = "123456";

  params["operationParams"] = operationParams;
  request["id"] = getId();
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );

  request["id"] = getId();
  request["method"] = "ref";
  params.clear();
  params["object"] = objId;
  params["sessionId"] = "12345";
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );

  request["id"] = getId();
  request["method"] = "describe";
  params.clear();
  params["object"] = objId;
  params["sessionId"] = "12345";
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isMember ("type") );
  BOOST_CHECK (response["result"]["type"].asString () == "WebRtcEndpoint" );

  std::string sessionId = "123456";
  request.removeMember ("id");
  request["id"] = getId();
  request["method"] = "release";
  params.clear();
  params["object"] = objId;
  params["sessionId"] = sessionId;

  params["operationParams"] = operationParams;
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (response["result"]["sessionId"].asString () == sessionId );
}
Esempio n. 27
0
void MNMClass::requestGlobal(uint8_t _global) {
  sendRequest(MNM_GLOBAL_REQUEST_ID, _global);
}
Esempio n. 28
0
static int test_001(TestState *state)
{
    TestState state2;
    int listener1, listener2, connection1, count, result;
    char response[1024];

    initState(&state2, "  Subtest", state);

    if (startTest(&state2, "LISTEN")) {
        if (serialRequest(&state2, "LISTEN:HTTP,/robot*"))
            checkSerialResponse(&state2, "=S,^i", &listener1);
    }

    beginGroup(&state2);

    if (startTest(&state2, "PATH of a listener")) {
        if (!skipTest(&state2) && serialRequest(&state2, "PATH:%d", listener1))
            checkSerialResponse(&state2, "=S,/robot*");
    }

    if (startTest(&state2, "Send request to WX module")) {
        if (!skipTest(&state2)) {
            if (sendRequest(&state->moduleAddr, "POST", "/robot?gto=f", "") >= 0)
                passTest(&state2, "");
            else
                failTest(&state2, "");
        }
    }

    beginGroup(&state2);

    if (startTest(&state2, "POLL for incoming POST request")) {
        if (!skipTest(&state2)) {
            do {
                if (!serialRequest(&state2, "POLL"))
                    break;
            } while (!waitAndCheckSerialResponse(&state2, "=N,0,0", "=P,^i,^i", &connection1, &listener2));
        }
    }

    beginGroup(&state2);

    if (startTest(&state2, "listener handle returned by POLL")) {
        if (listener1 == listener2)
            passTest(&state2, "");
        else
            failTest(&state2, ": got %d", listener2);
    }

    if (startTest(&state2, "PATH of a connection")) {
        if (!skipTest(&state2) && serialRequest(&state2, "PATH:%d", connection1))
            checkSerialResponse(&state2, "=S,/robot");
    }

    if (startTest(&state2, "ARG")) {
        if (!skipTest(&state2) && serialRequest(&state2, "ARG:%d,gto", connection1))
            checkSerialResponse(&state2, "=S,f");
    }

    if (startTest(&state2, "REPLY")) {
        if (!skipTest(&state2) && serialRequest(&state2, "REPLY:%d,200", connection1))
            checkSerialResponse(&state2, "=S,^i", &count);
    }

    if (startTest(&state2, "POLL for send complete")) {
        if (!skipTest(&state2)) {
            do {
                if (!serialRequest(&state2, "POLL"))
                    break;
            } while (!waitAndCheckSerialResponse(&state2, "=N,0,0", "=S,^i,0", &count, &listener2));
        }
    }

    if (startTest(&state2, "Receive response from WX")) {
        if (!skipTest(&state2)) {
            if (receiveResponse((uint8_t *)response, sizeof(response), &result) >= 0)
                passTest(&state2, "");
            else
                failTest(&state2, "");
        }
    }

    if (startTest(&state2, "CLOSE")) {
        if (!skipTest(&state2) && serialRequest(&state2, "CLOSE:%d", listener1))
            checkSerialResponse(&state2, "=S,0");
    }

    testResults(&state2);

    return state2.testPassed;
}
Esempio n. 29
0
bool LeafClientHandler::rebindSiblingPeer(
        int type,
        UUIDPtr& uuid,
        CellIDPtr& cellID,
        CellIDPtr& parentCellID,
        EndpointPtr& endpoint,
        SAPInfoPtr& discoverySAP,
        SAPInfoPtr& meshSAP,
        SAPInfoPtr& ftSAP,
        ACE_Message_Block* mb) {
    ACE_GUARD_RETURN(ACE_SYNCH_RECURSIVE_MUTEX, ace_mon, m_lock, false);
    SthenoPacket *packet = 0;
    if (m_debugLeafClientHandler) {
        ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)INFO: LeafClientHandler:rebindSiblingPeer(): PEER(%s,%s)\n"),
                uuid->toString().c_str(),
                cellID->toString().c_str()));
    }

    UUIDPtr srcCellID(new CellID(m_cellID.get()));
    UUIDPtr dstCellID(new CellID(m_cellID.get()));
    EndpointPtr followerEndpoint;
    UUIDPtr runtimeUUID;
    m_mesh->getUUID(runtimeUUID);
    packet = new RebindMeshPacket(runtimeUUID,
            srcCellID,
            m_uuid,
            dstCellID,
            0,
            type,
            uuid,
            cellID,
            parentCellID,
            endpoint,
            followerEndpoint,
            discoverySAP,
            meshSAP,
            ftSAP,
            mb);
    RequestEngine<SthenoPacket*>::RequestPtr* request = sendRequest(packet, 0);
    delete packet;
    if (request == 0) {
        ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)ERROR: LeafClientHandler:rebindSiblingPeer() - Request failed\n")));
        return 0;
    }
    //ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)Before wait future\n");
    ACE_Time_Value timeout = ACE_OS::gettimeofday();
    ACE_Time_Value delta;
    delta.msec(JOIN_CELL_TIMEOUT_MS);
    timeout += delta;
    list<SthenoPacket*>* results = request->get()->waitFuture(0);
    ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T) LeafClientHandler:rebindSiblingPeer() After future\n")));
    //ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)After future\n");
    if (results != 0 && results->size() > 0) {
        RebindMeshReplyPacket* replyPacket = static_cast<RebindMeshReplyPacket*> (results->front());
        bool status = replyPacket->getJoinResult();
        ListHelper<SthenoPacket*>::deleteList(results);
        return status;
    } else {
        ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t|%T)ERROR: LeafClientHandler::rebindSiblingPeer() - No response\n")));
    }

    return false;
}
// . returns false if blocked, true otherwise
// . sets g_errno on error (and m_errno)
// . k is a hint of which msg0 to use
// . if k is -1 we do a complete scan to find available m_msg0[x]
bool Msg51::sendRequests ( int32_t k ) {

 sendLoop:

	// bail if none left, return false if still waiting
	if ( m_numRequests - m_numReplies >= m_numSlots ) return false;

	bool isDone = false;
	if ( m_nexti >= m_numDocIds ) isDone = true;

	// any requests left to send?
	if ( isDone ) {
		// we are still waiting on replies, so we blocked...
		if ( m_numRequests > m_numReplies ) return false;
		// we are done!
		return true;
	}

	// sanity check
	if ( m_clusterLevels[m_nexti] <  0      ||
	     m_clusterLevels[m_nexti] >= CR_END   ) {
		gbshutdownLogicError(); }

	// skip if we already got the rec for this guy!
	if ( m_clusterLevels[m_nexti] != CR_UNINIT ) {
		m_nexti++;
		goto sendLoop;
	}

	// . check our quick local cache to see if we got it
	// . use a max age of 1 hour
	// . this cache is primarly meant to avoid repetetive lookups
	//   when going to the next tier in Msg3a and re-requesting cluster
	//   recs for the same docids we did a second ago
	RdbCache *c = &s_clusterdbQuickCache;
	if ( ! s_cacheInit ) c = NULL;
	int32_t      crecSize;
	char     *crecPtr = NULL;
	key96_t     ckey = (key96_t)m_docIds[m_nexti];
	bool found = false;
	if ( c )
		found = c->getRecord ( m_collnum    ,
				       ckey      , // cache key
				       &crecPtr  , // pointer to it
				       &crecSize ,
				       false     , // do copy?
				       3600      , // max age in secs
				       true      , // inc counts?
				       NULL      );// cachedTime
	if ( found ) {
		// sanity check
		if ( crecSize != sizeof(key96_t) ) gbshutdownLogicError();
		m_clusterRecs[m_nexti] = *(key96_t *)crecPtr;
		// it is no longer CR_UNINIT, we got the rec now
		m_clusterLevels[m_nexti] = CR_GOT_REC;
		// debug msg
		//logf(LOG_DEBUG,"query: msg51 getRec k.n0=%" PRIu64" rec.n0=%" PRIu64,
		//     ckey.n0,m_clusterRecs[m_nexti].n0);
		m_nexti++;
		goto sendLoop;
	}

	// . do not hog all the udpserver's slots!
	// . must have at least one outstanding reply so we can process
	//   his reply and come back here...
	if ( g_udpServer.getNumUsedSlots() > 1000 &&
	     m_numRequests > m_numReplies ) return false;

	// find empty slot
	int32_t slot ;

	// ignore bogus hints
	if ( k >= m_numSlots ) k = -1;

	// if hint was provided use that
	if ( k >= 0 && ! m_slot[k].m_inUse )
		slot = k;
	// otherwise, do a scan for the empty slot
	else {
		for ( slot = 0 ; slot < m_numSlots ; slot++ )
			// break out if available
			if(!m_slot[slot].m_inUse)
				break;
	}

	// sanity check -- must have one!!
	if ( slot >= m_numSlots ) gbshutdownLogicError();

	// send it, returns false if blocked, true otherwise
	sendRequest ( slot );

	// update any hint to make our loop more efficient
	if ( k >= 0 ) k++;
	
	goto sendLoop;
}