Esempio n. 1
0
ssize_t NHandsFree::
ParseLine(char *buf, size_t len)
{
	size_t pos = 0;
	char c;

	/* Are we looking at white space?  Trim it! */
	c = buf[0];
	assert(c);
	if (IsWS(c) || IsNL(c)) {
		do {
			c = buf[++pos];
		} while ((pos < len) && (IsWS(c) || IsNL(c)));
		return pos;
	}

	/* Is there a newline anywhere in the buffer? */
	for (pos = 1; pos < len; pos++) {
		if (IsNL(buf[pos])) {
			buf[pos] = '\0';

			ndebug::out(ndebug::LOG_DEBUG,
				    "NHandsFree: << %s", buf);

			if (!ParseResponse(buf))
				return -1;

			return pos + 1;
		}
	}

	/* No newline, nothing to consume */
	return 0;
}
Esempio n. 2
0
// 接收响应头
bool CTyHttpClient::RecvResponseHead()
{
    char *pszRequest = new char[1024*10];
    char *pCurrent = pszRequest;
    while(!IsClosed())
    {
        // 每次只接收1字节
        if (1 == Select_Receive(pCurrent, 1))
        {
            ++pCurrent;

            // 接完4个字节后,可判断是否已全接完
            if((pCurrent>pszRequest+4) && (memcmp(pCurrent-4, "\r\n\r\n", 4)==0))
            {
                *pCurrent = '\0';
                break;
            }
        }
    }

    bool bRet = ParseResponse(pszRequest);
    delete [] pszRequest;

    return bRet;
}
Esempio n. 3
0
bool Printer::Idle( void ) {
    string str;
    bool is_connected;

    while ( ( str = ReadResponse() ) != "" )
        ParseResponse( str );

    if ( m_view ) {
        while ( ( str = ReadLog() ) != "" )
            m_view->comm_log( str );

        while ( ( str = ReadErrorLog() ) != "" ) {
            alert( str.c_str() );
        }
    }

    if ( ( is_connected = IsConnected() ) != was_connected ) {
        was_connected = is_connected;
        signal_serial_state_changed.emit( is_connected ? SERIAL_CONNECTED : SERIAL_DISCONNECTED );
    }

    if ( waiting_temp && --temp_countdown == 0 &&
            m_model && m_model->settings.get_boolean("Misc","TempReadingEnabled") ) {
        UpdateTemperatureMonitor();
        temp_countdown = 100;
        waiting_temp = false;
    }

    return true;
}
Esempio n. 4
0
int CSubscriptionMgr::Subscribe(const vector<string> msgNames, bool subscribe)
{
	TEX0_DEBUG_TRACE("subscribe?[%s]", subscribe ? "yes" : "no");

	//获取请求地址
	string url = m_Interface->GetUrl();
	if (url.empty())
	{
		TEX0_LOG_ERROR("Get server url failed, please login first");
		return TEX0_URL_EMPTY;
	}
	if (subscribe)
	{
		url.append("/action.cgi?ActionID=WEB_SubscribeMsgAPI");
	} 
	else
	{
		url.append("/action.cgi?ActionID=WEB_UnSubscribeMsgAPI");
	}

	//设置请求参数
	Json::Value send;
	for (unsigned int i=0; i<msgNames.size(); ++i)
	{
		send["aszMsgIDs"].append(msgNames.at(i));
	}

	REQUEST_OPTIONS request;
	request.strUrl = url;
	request.uiTimeOut = TIMEOUT_2S;
	request.uiVersion = VERSION_1_1;
	request.uiReqMode = MODE_POST;
	request.strReqData = send.toStyledString();
	request.ReqHeader.push_back(m_Interface->GetCookie());

	//发送请求
	string rspBody;
	string rspHeader;
	int ret = eSDK_HTTP_SendRequest(request, rspBody, rspHeader);
	if (RET_OK != ret)
	{
		TEX0_LOG_ERROR("Send http request failed, url[%s] time out[%d] http version[%d] mode[%d] data[%s], error code[%d]", 
			request.strUrl.c_str(), request.uiTimeOut, request.uiVersion, request.uiReqMode, request.strReqData.c_str(), ret);
		return TEX0_SEND_REQUEST_FAILED;
	}

	//解析响应
	bool success;
	int id, code;
	string data, paras;
	ret = ParseResponse(rspBody, success, data, id, code, paras);
	if (TEX0_SUCCESS != ret)
	{
		TEX0_LOG_ERROR("Invalid response, not json form or missing something[%s]", rspBody.c_str());
		return ret;
	}

	return success ? TEX0_SUCCESS : code;
}
Esempio n. 5
0
void OnlineCrossFetcher::Do()
{
  m_mwmPoints.clear();
  if (m_request.RunHTTPRequest() && m_request.error_code() == 200 && !m_request.was_redirected())
    ParseResponse(m_request.server_response(), m_mwmPoints);
  else
    LOG(LWARNING, ("Can't get OSRM server response. Code: ", m_request.error_code()));
}
Esempio n. 6
0
int CLoginMgr::Logout()
{
    TEX0_DEBUG_TRACE("");

    //获取请求地址
    string url = m_Interface->GetUrl();
    if (url.empty())
    {
        TEX0_LOG_ERROR("Get server url failed, please login first");
        return TEX0_URL_EMPTY;
    }
    url.append("/action.cgi?ActionID=WEB_LogoutAPI");

    //设置请求参数
    REQUEST_OPTIONS request;
    request.strUrl = url;
    request.uiTimeOut = TIMEOUT_2S;
    request.uiVersion = VERSION_1_1;
    request.uiReqMode = MODE_POST;
    request.ReqHeader.push_back(m_Interface->GetCookie());

    //发送请求
    string rspBody;
    string rspHeader;
    int ret = eSDK_HTTP_SendRequest(request, rspBody, rspHeader);
    if (RET_OK != ret)
    {
        TEX0_LOG_ERROR("Send http request failed, url[%s] time out[%d] http version[%d] mode[%d] data[%s], error code[%d]",
                       request.strUrl.c_str(), request.uiTimeOut, request.uiVersion, request.uiReqMode, request.strReqData.c_str(), ret);
        return TEX0_SEND_REQUEST_FAILED;
    }

    //解析响应
    bool success;
    int id, code;
    string data, paras;
    ret = ParseResponse(rspBody, success, data, id, code, paras);
    if (TEX0_SUCCESS != ret)
    {
        TEX0_LOG_ERROR("Invalid response, not json form or missing something[%s]", rspBody.c_str());
        return ret;
    }

    if (success)
    {
        m_Interface->SetUrl("");
        m_Interface->SetCookie("");
        //m_Interface->StopKeepAlive(); 2015/1/8 SDK调用者通过keepAlive接口自行控制保活
        return TEX0_SUCCESS;
    }
    else
    {
        TEX0_LOG_ERROR("Logout failed, error code[%d]", code);
        return code;
    }
}
void LicenseSystem::HandleActivationResult(StringHash eventType, VariantMap& eventData)
{
    VariantMap eventDataOut;

    if (serverActivation_->GetError().Length())
    {
        String errorMessage;
        errorMessage.AppendWithFormat("There was an error contacting the activation server\n\n%s", serverActivation_->GetError().CString());

        eventDataOut[LicenseActivationError::P_MESSAGE] = errorMessage;
        SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);
        return;
    }
    else
    {
        LicenseParse parse;
        int code = ParseResponse(serverActivation_->GetResponse(), parse);

        if (code == 0)
        {
            Activate(key_, parse);
            SendEvent(E_LICENSE_ACTIVATIONSUCCESS);
        }
        else if (code == 1)
        {
            // TODO: check for CLI and prompt to use CLI command to return license
            String message = "Activations Exceeded:\nThis key has 2 activations in use.\n\nPlease return a license from Atomic Editor - Manage License menu on one of these active computers.\n\nIf you are unable to do so, please contact [email protected] providing the key to reset it";
            eventDataOut[LicenseActivationError::P_MESSAGE] = message;
            SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);

        }
        else if (code == 2)
        {
            String message = "License Error:\nThere was a problem with the license key.\n\nPlease check the key and try again.\n\nIf the problem persists please contact [email protected]";
            eventDataOut[LicenseActivationError::P_MESSAGE] = message;
            SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);


        }
        else if (code == 3)
        {
            String message ="Activation Server Error:\nThere was an error on the activation server\n\nIf the problem persists please contact [email protected]";
            eventDataOut[LicenseActivationError::P_MESSAGE] = message;
            SendEvent(E_LICENSE_ACTIVATIONERROR, eventDataOut);
        }

    }

    UnsubscribeFromEvents(serverActivation_);
    serverActivation_ = 0;
}
Esempio n. 8
0
int CLoginMgr::RequestCertification(const string userName, const string password)
{
    TEX0_DEBUG_TRACE("user[%s]", userName.c_str());

    //获取请求地址
    string url = m_Interface->GetUrl();
    if (url.empty())
    {
        TEX0_LOG_ERROR("Get server url failed, please login first");
        return TEX0_URL_EMPTY;
    }
    url.append("/action.cgi?ActionID=WEB_RequestCertificateAPI");

    //设置请求参数
    Json::Value send;
    send["user"] = userName;
    send["password"] = password;

    REQUEST_OPTIONS request;
    request.strUrl = url;
    request.uiTimeOut = TIMEOUT_2S;
    request.uiVersion = VERSION_1_1;
    request.uiReqMode = MODE_POST;
    request.strReqData = send.toStyledString();
    request.ReqHeader.push_back(m_Interface->GetCookie());

    //发送请求
    string rspBody;
    string rspHeader;
    int ret = eSDK_HTTP_SendRequest(request, rspBody, rspHeader);
    if (RET_OK != ret)
    {
        TEX0_LOG_ERROR("Send http request failed, url[%s] time out[%d] http version[%d] mode[%d], error code[%d]",
                       request.strUrl.c_str(), request.uiTimeOut, request.uiVersion, request.uiReqMode, ret);
        return TEX0_SEND_REQUEST_FAILED;
    }

    //解析响应
    bool success;
    int id, code;
    string data, paras;
    ret = ParseResponse(rspBody, success, data, id, code, paras);
    if (TEX0_SUCCESS != ret)
    {
        TEX0_LOG_ERROR("Invalid response, not json form or missing something[%s]", rspBody.c_str());
        return ret;
    }

    return success ? TEX0_SUCCESS : code;
}
// this is FormatMatchesCapabilities for Audio
CodecSpecifier* PV2WayMIO::FormatMatchesCapabilities(const PVAsyncInformationalEvent& aEvent)
{
    PVMFFormatType aMimeString;
    int aMedia_Type = 0;
    ParseResponse(aEvent, aMimeString, aMedia_Type);
    // compare to what in iFormats instead.
    CodecSpecifier* formatInList = FormatInList(aMimeString);
    if (!formatInList)
    {
        OutputInfo("Format %s does not match application capability\n", aMimeString.getMIMEStrPtr());
    }
    else
    {
        OutputInfo("Format %s matches application capabilities\n", aMimeString.getMIMEStrPtr());
    }

    return formatInList;
}
Esempio n. 10
0
int CSubscriptionMgr::RefreshMailbox(TerminalState &terminalState, vector<MsgStruct> &msgStruct)
{
	//获取请求地址
	string url = m_Interface->GetUrl();
	if (url.empty())
	{
		TEX0_LOG_ERROR("RefreshMailbox::Get server url failed, please login first");
		return TEX0_URL_EMPTY;
	}
	url.append("/action.cgi?ActionID=WEB_GetMailboxDataAPI");

	//设置请求参数
	REQUEST_OPTIONS request;
	request.strUrl = url;
	request.uiTimeOut = TIMEOUT_2S;
	request.uiVersion = VERSION_1_1;
	request.uiReqMode = MODE_POST;
	request.ReqHeader.push_back(m_Interface->GetCookie());

	//发送请求
	string rspBody;
	string rspHeader;
	int ret = eSDK_HTTP_SendRequest(request, rspBody, rspHeader);
	if (RET_OK != ret)
	{
		TEX0_LOG_ERROR("RefreshMailbox::Send http request failed, url[%s] time out[%d] http version[%d] mode[%d] data[%s], error code[%d]", 
			request.strUrl.c_str(), request.uiTimeOut, request.uiVersion, request.uiReqMode, request.strReqData.c_str(), ret);
		return TEX0_SEND_REQUEST_FAILED;
	}

	//解析响应
	bool success;
	string data;
	int id, code;
	string paras;
	ret = ParseResponse(rspBody, success, data, id, code, paras);
	if (TEX0_SUCCESS != ret)
	{
		TEX0_LOG_ERROR("RefreshMailbox::Invalid response, not json form or missing something[%s]", rspBody.c_str());
		return ret;
	}

	return success ? ParseMessage(data, terminalState, msgStruct) : code;
}
Esempio n. 11
0
TEST_RESULT TestTimeoutResponseMessage()
{
	{
		std::cout << "just a response" << std::endl;
		std::stringstream messageToBeSent;
		CommandTimeoutResponse * req  = new CommandTimeoutResponse("allocate-channel");
		req->Write(messageToBeSent);
		std::cout << messageToBeSent.str() << std::endl;
	}

	{
		std::cout << "response with result" << std::endl;
		std::stringstream messageToBeSent;
		CommandTimeoutResponse * req  = new CommandTimeoutResponse("deallocate-channel");
		req->SetError(ERRORCODE_WRONG_CHANNELID, "Channel is wrong");
		req->Write(messageToBeSent);
		std::cout << messageToBeSent.str() << std::endl;
	}

	{
		std::cout << "response to object and get all the fields" << std::endl;
		std::stringstream messageToBeSent;
		CommandTimeoutResponse * req  = new CommandTimeoutResponse("super-man-tag");
		req->SetError(ERRORCODE_CHANNELID_ALREADY_OCCUPIED, "Channel is occupied. try another one");
		req->Write(messageToBeSent);
		std::cout << messageToBeSent.str() << std::endl;

		pugi::xml_document* doc = new pugi::xml_document();
		ParseResponse(doc, ( char*)(messageToBeSent.str().c_str()));
		CommandTimeoutResponse * res = new CommandTimeoutResponse(doc);

		std::cout << "channel id" << res->GetMessageName() << std::endl;
		ErrorCode errc;
		const char * errstr;
		res->GetError(errc, errstr);
		std::cout << "err code" <<  errc << std::endl;
		std::cout << "err str" <<  errstr << std::endl;

	}

	return PASSED;
}
Esempio n. 12
0
Weather::ReturnVals Weather::GetVals(const char * key, uint32_t zip, const char * pws, bool usePws) const
{
	ReturnVals vals = {0};
	EthernetClient client;
	if (client.connect(m_wundergroundAPIHost, 80))
	{
		char getstring[255];
		trace(F("Connected\n"));
		if (usePws)
			snprintf(getstring, sizeof(getstring), "GET http://%s/api/%s/yesterday/conditions/q/pws:%s.json HTTP/1.1\r\n",m_wundergroundAPIHost, key, pws);
		else
			snprintf(getstring, sizeof(getstring), "GET http://%s/api/%s/yesterday/conditions/q/%ld.json HTTP/1.1\r\n",m_wundergroundAPIHost, key, (long) zip);

		//trace("GetString:%s\n",getstring);
		client.write((uint8_t*) getstring, strlen(getstring));
		
		//send host header
		snprintf(getstring, sizeof(getstring), "Host: %s\r\nConnection: close\r\n\r\n",m_wundergroundAPIHost);
		//trace("GetString:%s\n",getstring);
		client.write((uint8_t*) getstring, strlen(getstring));

		ParseResponse(client, &vals);
		vals.resolvedIP=client.GetIpAddress();

		client.stop();
		if (!vals.valid)
		{
			if (vals.keynotfound)
				trace("Invalid WUnderground Key\n");
			else
				trace("Bad WUnderground Response\n");
		}
	}
	else
	{
		trace(F("connection failed\n"));
		client.stop();
	}
	return vals;
}
Esempio n. 13
0
void LicenseSystem::HandleVerification(StringHash eventType, VariantMap& eventData)
{

    CurlRequest* request = (CurlRequest*) (eventData[CurlComplete::P_CURLREQUEST].GetPtr());

    bool licenseError = false;
    bool resetLicense = false;

    if (serverVerification_.NotNull())
    {
        assert(request == serverVerification_);

        if (serverVerification_->GetError().Length())
        {
            ATOMIC_LOGERRORF("Unable to verify with server: %s", serverVerification_->GetError().CString());
        }
        else
        {
            LicenseParse parse;
            int code = ParseResponse(serverVerification_->GetResponse(), parse);

            if (code == 4)
            {
                // not activated
                resetLicense = true;
                licenseError = true;
            }
            else if (code == 2)
            {
                // something is wrong with the key
                resetLicense = true;
                licenseError = true;

            }
            else if (code == 3)
            {
                // something is wrong on the activation server
                licenseError = true;
            }
            else if (code == 1)
            {
                // exceeded code, should not happen here as we aren't activating
                resetLicense = true;
                licenseError = true;
            }
            else if (code == 0)
            {
                // we should raise an error if there is a mismatch between local and server keys
                // when the local says there are more enabled than server?
                // otherwise, they could be being added

                bool mismatch = false;

                if (parse.licenseWindows_ != licenseWindows_)
                    mismatch = true;

                if (parse.licenseMac_ != licenseMac_)
                    mismatch = true;

                if (parse.licenseWindows_ != licenseWindows_)
                    mismatch = true;

                if (parse.licenseAndroid_ != licenseAndroid_)
                    mismatch = true;

                if (parse.licenseIOS_ != licenseIOS_)
                    mismatch = true;

                if (parse.licenseHTML5_ != licenseHTML5_)
                    mismatch = true;

                if (parse.licenseModule3D_ != licenseModule3D_)
                    mismatch = true;

                if (mismatch)
                {
                    ATOMIC_LOGERROR("License Mismatch, reseting");
                    licenseWindows_ = parse.licenseWindows_;
                    licenseMac_ = parse.licenseMac_;
                    licenseAndroid_ = parse.licenseAndroid_;
                    licenseIOS_= parse.licenseIOS_;
                    licenseHTML5_= parse.licenseHTML5_;
                    licenseModule3D_= parse.licenseModule3D_;

                    SaveLicense();
                }

                CreateOrUpdateLicenseCache();

                SendEvent(E_LICENSE_SUCCESS);
            }

        }

        UnsubscribeFromEvents(serverVerification_);
        serverVerification_ = 0;
    }

    if (resetLicense)
    {
        RemoveLicense();
        ResetLicense();
    }

    if (licenseError)
    {
        ATOMIC_LOGINFO("There was an issue with the atomic-cli activation.  Please reactivate or contact [email protected] if this problem persists");
        SendEvent(E_LICENSE_ERROR);
    }

}
Esempio n. 14
0
dt_result_t btTracker::CheckResponse()
{
  const char *pdata;
  ssize_t r;
  size_t q, hlen, dlen;

  r = m_response_buffer.FeedIn(m_sock);
  m_last_timestamp = now;

  if( r > 0 ){
    // connection is still open; may have more data coming
    return DT_NORMAL;
  }

  q = m_response_buffer.Count();

  if( !q ){
    int error = 0;
    socklen_t n = sizeof(error);
    if( getsockopt(m_sock, SOL_SOCKET, SO_ERROR, &error, &n) < 0 )
      error = errno;
    if( error ){
      CONSOLE.Warning(2, "warn, received nothing from tracker at %s:  %s",
        m_spec->url, strerror(error));
    }else{
      CONSOLE.Warning(2, "warn, received nothing from tracker at %s",
        m_spec->url);
    }
    Reset();  // try again
    return DT_FAILURE;
  }

  hlen = HttpSplit(m_response_buffer.BasePointer(), q, &pdata, &dlen);

  if( !hlen ){
    CONSOLE.Warning(2, "warn, no HTTP header in response from tracker at %s",
      m_spec->url);
    return DT_FAILURE;
  }

  r = HttpGetStatusCode(m_response_buffer.BasePointer(), hlen);
  if( r != 200 ){
    if( r == 301 || r == 302 || r == 303 || r == 307 ){
      char *tmpurl = (char *)0, *c;
      tracker_spec *tmpspec;

      if( HttpGetHeader(m_response_buffer.BasePointer(), hlen, "Location",
                        &tmpurl) < 0 ){
        if( errno ){
          CONSOLE.Warning(2,
            "Error parsing redirect response from tracker at %s:  %s",
            m_spec->url, strerror(errno));
        }else{
          CONSOLE.Warning(2,
            "warn, redirect with no location from tracker at %s", m_spec->url);
        }
        if( tmpurl ) delete []tmpurl;
        return DT_FAILURE;
      }

      if( !(tmpspec = new tracker_spec) ){
        CONSOLE.Warning(1,
          "warn, could not allocate memory for tracker redirect from %s",
          m_spec->url);
        errno = ENOMEM;
        delete []tmpurl;
        return DT_FAILURE;
      }

      if( (c = strstr(tmpurl, "?info_hash=")) ||
          (c = strstr(tmpurl, "&info_hash=")) ){
        *c = '\0';
      }
      if( UrlSplit(tmpurl, &tmpspec->host, &tmpspec->port,
                   &tmpspec->request) < 0 ){
        CONSOLE.Warning(1,
          "warn, error parsing redirected tracker URL from %s (%s):  %s",
          m_spec->url, tmpurl, errno ? strerror(errno) : "invalid format");
        delete tmpspec;
        delete []tmpurl;
        return DT_FAILURE;
      }else{
        CONSOLE.Debug("tracker at %s redirected%s to %s",
          m_spec->url, (r == 301) ? " permanently" : "", tmpurl);
        if( (tmpspec->url = new char[strlen(tmpurl) + 1]) )
          strcpy(tmpspec->url, tmpurl);
        else{
          CONSOLE.Warning(1,
            "warn, could not allocate memory for tracker redirect from %s",
            m_spec->url);
          errno = ENOMEM;
          delete tmpspec;
          delete []tmpurl;
          return DT_FAILURE;
        }
        delete []tmpurl;
        Reset();
        m_redirect = m_spec;
        m_spec = tmpspec;
        if( BuildBaseRequest() < 0 ){
          delete m_spec;
          m_spec = m_redirect;
          m_redirect = (tracker_spec *)0;
          return DT_FAILURE;
        }else if( r == 301 ){  // moved permanently
          delete m_redirect;
          m_redirect = (tracker_spec *)0;
        }
      }

      if( Connect() < 0 ){
        Reset();
        delete m_spec;
        m_spec = m_redirect;
        m_redirect = (tracker_spec *)0;
        return DT_FAILURE;
      }else return DT_NORMAL;
    }else if( r >= 400 ){
      CONSOLE.Warning(2, "Tracker response code %d from %s%s", r, m_spec->url,
        (r >= 500) ? "" :
          "; the torrent is not registered on this tracker"
          " or may have been removed.");
      if( pdata && dlen ){  // write(STDERR_FILENO, pdata, dlen);
        char data[dlen + 1];
        memcpy(data, pdata, dlen);
        data[dlen] = '\0';
        CONSOLE.Warning(0, "Tracker response data DUMP:");
        CONSOLE.Warning(0, "%s", data);
        CONSOLE.Warning(0, "== DUMP OVER==");
      }
      m_interval = (m_default_interval > 300) ? m_default_interval : 300;
      m_f_started = 0;
      return DT_FAILURE;
    }else{
      m_f_started = 0;
      return DT_FAILURE;
    }
  }

  m_f_started = m_f_stop ? 0 : 1;
  m_refuse_click = 0;
  m_ok_click++;

  if( !pdata ){
    CONSOLE.Warning(2, "warn, received no response data from tracker at %s",
      m_spec->url);
    return DT_FAILURE;
  }
  return ParseResponse(pdata, dlen);
}
Esempio n. 15
0
TEST_RESULT TestAllocateNotificationMessage()
{
	std::cout << "create noti with no cid" << std::endl;
	{
		std::stringstream messageToBeSent;
		Message * noti  = new AllocateNotification("gutentag");

		noti->Write(messageToBeSent);
		std::cout << messageToBeSent.str() << std::endl;
	}

	std::cout << "create noti with cid" << std::endl;
	{
		std::stringstream messageToBeSent;
		Message * noti = new AllocateNotification("gutentag", 15);

		noti->Write(messageToBeSent);
		std::cout << messageToBeSent.str() << std::endl;
	}

	std::cout << "create noti with error" << std::endl;
	{
		std::stringstream messageToBeSent;
		Notification * noti = new AllocateNotification("gutentag", 15);
		noti->SetError(ERRORCODE_WRONG_CHANNELID, "crab happened");
		noti->Write(messageToBeSent);
		std::cout << messageToBeSent.str() << std::endl;
	}

	std::cout << "create Allocate noti with error and cid" << std::endl;
	{
		std::stringstream messageToBeSent;
		AllocateNotification * noti = new AllocateNotification("gutentag", 15);
		noti->SetError(ERRORCODE_WRONG_CHANNELID, "crab happened 2");
		noti->Write(messageToBeSent);
		std::cout << messageToBeSent.str() << std::endl;

		pugi::xml_document* doc = new pugi::xml_document();
		ParseResponse(doc, ( char*)(messageToBeSent.str().c_str()));
		AllocateNotification * res = new AllocateNotification(doc);

		std::cout << "channel id" << res->GetChannelId() << std::endl;
		ErrorCode errc;
		const char * errstr;
		res->GetError(errc, errstr);
		std::string messageName = res->GetMessageName();

		std::cout << "message name" << messageName << std::endl;
		std::cout << "err code" << errc << std::endl;
		std::cout << "err str" << errstr << std::endl;


	}

	std::cout << "test static functionality" << std::endl;
		{
			std::stringstream messageToBeSent;
			AllocateNotification * noti = new AllocateNotification("gutentag", 25);
			noti->SetError(ERRORCODE_WRONG_CHANNELID, "crab happened 3");
			noti->Write(messageToBeSent);
			std::cout << messageToBeSent.str() << std::endl;

			pugi::xml_document* doc = new pugi::xml_document();
			ParseResponse(doc, ( char*)(messageToBeSent.str().c_str()));

			if (Notification::NOTIFICATIONTTYPE_ALLOCATE == Notification::GetNotificationType(doc))
				std::cout << "type obtained properly" << std::endl;

			std::cout << "tag" << Notification::GetNotificationTag(doc) << std::endl;

		}


	return PASSED;

}
void LicenseSystem::HandleVerification(StringHash eventType, VariantMap& eventData)
{

    CurlRequest* request = (CurlRequest*) (eventData[CurlComplete::P_CURLREQUEST].GetPtr());

    if (serverVerification_.NotNull())
    {
        assert(request == serverVerification_);

        if (serverVerification_->GetError().Length())
        {
            LOGERRORF("Unable to verify with server: %s", serverVerification_->GetError().CString());
        }
        else
        {
            LicenseParse parse;
            int code = ParseResponse(serverVerification_->GetResponse(), parse);

            // Not activated
            if (code == 4)
            {

            }
            else if (code == 2)
            {
                // something is wrong with the key
                LOGERRORF("Error with product key");

                RemoveLicense();
                ResetLicense();
                UIModalOps* ops = GetSubsystem<UIModalOps>();
                ops->Hide();
                ops->ShowActivation();

            }
            else if (code == 3)
            {
                // something is wrong on the activation server
                key_ = "";
            }
            else if (code == 1)
            {
                // exceeded code, should not happen here as we aren't activating
                key_ = "";
            }
            else if (code == 0)
            {
                // we should raise an error if there is a mismatch between local and server keys
                // when the local says there are more enabled than server?
                // otherwise, they could be being added

                bool mismatch = false;

                if (parse.licenseWindows_ != licenseWindows_)
                    mismatch = true;

                if (parse.licenseMac_ != licenseMac_)
                    mismatch = true;

                if (parse.licenseWindows_ != licenseWindows_)
                    mismatch = true;

                if (parse.licenseAndroid_ != licenseAndroid_)
                    mismatch = true;

                if (parse.licenseIOS_ != licenseIOS_)
                    mismatch = true;

                if (parse.licenseHTML5_ != licenseHTML5_)
                    mismatch = true;

                if (parse.licenseModule3D_ != licenseModule3D_)
                    mismatch = true;

                if (mismatch)
                {
                    LOGERROR("License Mismatch, reseting");
                    licenseWindows_ = parse.licenseWindows_;
                    licenseMac_ = parse.licenseMac_;
                    licenseAndroid_ = parse.licenseAndroid_;
                    licenseIOS_= parse.licenseIOS_;
                    licenseHTML5_= parse.licenseHTML5_;
                    licenseModule3D_= parse.licenseModule3D_;

                    SaveLicense();
                }

                //if (!HasPlatformLicense())
                //{
                //    UIModalOps* ops = GetSubsystem<UIModalOps>();
                //    if (!ops->ModalActive())
                //        ops->ShowPlatformsInfo();

               // }

            }

        }

        UnsubscribeFromEvents(serverVerification_);
        serverVerification_ = 0;
    }

}
Esempio n. 17
0
// Performs contact list retrieval
// Input:	csLogin=String with user's telephone number
//			csPwd=String with user's password
// Output:	Contact list
CMapStringToOb* CCopiagenda::RetrieveContacts(CString csLogin, CString csPwd)
{
	CMapStringToOb* pmsoList=NULL;

	CString csData;

	CString csCookie;

    CString csHeaders;
	CString csRetHeaders;
	CString csRetData;

	csData.Format("TM_ACTION=LOGIN&TM_LOGIN=%s&TM_PASSWORD=%s",csLogin,csPwd);
    csHeaders = "Content-type: application/x-www-form-urlencoded\r\n"
				"Accept-Encoding: gzip, deflate\r\n"
				"Host: copiagenda.movistar.es\r\n"
				"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n"
				"Connection: Keep-Alive\r\n";

	UINT nCode=PostHTTPS("https://copiagenda.movistar.es/cp/ps/Main/login/Agenda",(BYTE*)csData.GetBuffer(0),csData.GetLength(),csHeaders,csRetHeaders,csRetData);
	if(nCode == 302)
	{
		csCookie=GetCookies(csRetHeaders);
		CString csURL=GetLocation(csRetHeaders);
		csHeaders = "Accept-Encoding: gzip, deflate\r\n"
					"Host: copiagenda.movistar.es\r\n"
					"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n"
					"Connection: Keep-Alive\r\n";
		csHeaders += "Cookie: "+csCookie+"\r\n";

		nCode=GetHTTPS(csURL,csHeaders,csRetHeaders,csRetData);

		// We are asked to re-authenticate with user data + cookie and we receive a session token
		int nPosPwd=csRetData.Find("password\" value=");
		if(nPosPwd!=-1)
		{
			CString csPwdAux=csRetData.Mid(nPosPwd+16);
			int nPosPwd2=csPwdAux.Find(">");
			if(nPosPwd2!=-1)
			{
				CString csPwd2=csPwdAux.Left(nPosPwd2);

				csData.Format("password=%s&u=%s&d=movistar.es",csPwd2,csLogin);
				csHeaders = "Content-type: application/x-www-form-urlencoded\r\n"
							"Accept-Encoding: gzip, deflate\r\n"
							"Host: copiagenda.movistar.es\r\n"
							"Referer: https://copiagenda.movistar.es/cp/ps/Main/login/Verificacion?d=movistar.es\r\n"
							"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n"
							"Connection: Keep-Alive\r\n";
				csHeaders += "Cookie: "+csCookie+"\r\n";

				UINT nCode=PostHTTPS("https://copiagenda.movistar.es/cp/ps/Main/login/Authenticate",(BYTE*)csData.GetBuffer(0),csData.GetLength(),csHeaders,csRetHeaders,csRetData);

				int nPosTok=csRetData.Find("&t=");
				if(nPosTok!=-1)
				{
					CString csTokAux=csRetData.Mid(nPosTok+3);
					int nPosTok2=csTokAux.Find("\"");
					if(nPosTok2!=-1)
					{
						// We ask for the data in text format delimited with TABs
						CString csToken=csTokAux.Left(nPosTok2);
						CString csURL = "https://copiagenda.movistar.es/cp/ps/PSPab/preferences/ExportContacts?d=movistar.es&c=yes&u="+csLogin+"&t="+csToken;
						csData = "fileFormat=TEXT&charset=8859_1&delimiter=TAB";
						csHeaders = "Content-type: application/x-www-form-urlencoded\r\n"
									"Accept-Encoding: gzip, deflate\r\n"
									"Host: copiagenda.movistar.es\r\n"
									"Referer: https://copiagenda.movistar.es/cp/ps/Main/login/Verificacion?d=movistar.es\r\n"
									"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n"
									"Connection: Keep-Alive\r\n";
						csHeaders += "Cookie: "+csCookie+"\r\n";

						UINT nCode=PostHTTPS(csURL,(BYTE*)csData.GetBuffer(0),csData.GetLength(),csHeaders,csRetHeaders,csRetData);
						pmsoList = ParseResponse(csRetData);
					}
				}
			}
		}
	}

	return pmsoList;
}
Esempio n. 18
0
void PrefsLoader::LoadData(URL_ID url_id)
{
	if(m_parse_blocked)
		return;
	if (!m_descriptor)
		m_descriptor = m_serverURL->GetDescriptor(g_main_message_handler, TRUE);
	if (!m_descriptor)
		return;
	m_parse_blocked = TRUE;

	BOOL more(TRUE);
	unsigned long buf_len = 0;

	while (more && ((buf_len = m_descriptor->RetrieveData(more)) > 0))
	{
		const uni_char *data_buf =
			reinterpret_cast<const uni_char *>(m_descriptor->GetBuffer());

		ParseResponse(data_buf, UNICODE_DOWNSIZE(buf_len), more?TRUE:FALSE);
		m_descriptor->ConsumeData(buf_len);
	}
	m_parse_blocked = FALSE;
	if (m_serverURL->Status(TRUE) == URL_LOADED)
	{
		if(m_parseno == 0)
		{
			if (m_clean_all_update)
			{
				// If the clean_all attribute is used on the preferences element
				// then any existing hostname override can be affected by this update.
				// Since the m_hostnames string we pass to ->IsEnd() might end up in
				// a "Do you want to install updated overrides for these hosts?"-type
				// of dialog with APPROVE/DENY buttons, it's important that we signal
				// the scope of the update correctly.
				m_hostnames.Set("*");
			}
			// if endchecker is present, it is responsible for stopping or continuing the parser.
			if(m_checker && m_checker->IsEnd(m_hostnames.CStr()))
				;
			else
			{
				// Parse one more time to retrieve the preference values
				m_parseno++;
				delete m_descriptor;
				m_descriptor = m_serverURL->GetDescriptor(g_main_message_handler, TRUE);
				if (!m_descriptor)
					return;
				delete m_prl_parser;
				m_prl_parser = NULL;

				more = TRUE;
				buf_len = 0;

				while (more && ((buf_len = m_descriptor->RetrieveData(more)) > 0))
				{
					const uni_char *data_buf =
						reinterpret_cast<const uni_char *>(m_descriptor->GetBuffer());

					ParseResponse(data_buf, UNICODE_DOWNSIZE(buf_len), more?TRUE:FALSE);
					m_descriptor->ConsumeData(buf_len);
				}
			}
        	}
		FinishLoading(url_id);
	}
}