コード例 #1
0
ファイル: BridgeServer.cpp プロジェクト: Archie3d/sandboxer
void BridgeServer::onNewConnection()
{
    QLocalSocket *pSocket = m_pLocalServer->nextPendingConnection();

    delete m_pBridgeCommunicator;
    m_pBridgeCommunicator = new BridgeCommunicator(pSocket, this);
    connect(m_pBridgeCommunicator, SIGNAL(requestReceived(QVariant)), this, SIGNAL(requestReceived(QVariant)));
    connect(m_pBridgeCommunicator, SIGNAL(responseReceived(QVariant)), this, SIGNAL(responseReceived(QVariant)));
}
コード例 #2
0
ファイル: LoginWindow.cpp プロジェクト: 4ukuta/core
 LoginWindow::LoginWindow(QWidget * parent, Qt::WindowFlags f):QMainWindow(parent,f)
 {
   QWidget *widget = new QWidget(this);
   m_form.setupUi(widget);
   setCentralWidget(widget);
   connect(m_form.m_login, SIGNAL(clicked()), SLOT(okPressed()));
   connect(&m_query,SIGNAL(responseReceived(QString, QString,QString)),this,SLOT(responseReceived(QString,QString,QString)));
   connect(&m_query,SLOT(onManagerSslErrors()),&m_query,SIGNAL(errorReceived()));
   connect(&m_query,SLOT(onReplyError(QNetworkReply::NetworkError)),&m_query,SIGNAL(errorReceived()));
   connect(&m_query,SIGNAL(errorReceived()),this,SLOT(errorReceived()));
 }
コード例 #3
0
void IslInterface::processMessage(const IslMessage &item)
{
	qDebug() << QString::fromStdString(item.DebugString());
	
	switch (item.message_type()) {
		case IslMessage::ROOM_COMMAND_CONTAINER: {
			processRoomCommand(item.room_command(), item.session_id());
			break;
		}
		case IslMessage::GAME_COMMAND_CONTAINER: {
			emit gameCommandContainerReceived(item.game_command(), item.player_id(), serverId, item.session_id());
			break;
		}
		case IslMessage::SESSION_EVENT: {
			processSessionEvent(item.session_event(), item.session_id());
			break;
		}
		case IslMessage::RESPONSE: {
			emit responseReceived(item.response(), item.session_id());
			break;
		}
		case IslMessage::GAME_EVENT_CONTAINER: {
			emit gameEventContainerReceived(item.game_event_container(), item.session_id());
			break;
		}
		case IslMessage::ROOM_EVENT: {
			processRoomEvent(item.room_event()); break;
			break;
		}
		default: ;
	}
}
コード例 #4
0
void StreamingAudioClient::handle_typeconfirm(int type, int preset)
{
    m_type = (StreamingAudioType)type;
    m_preset = preset;
    m_responseReceived = true;
    emit responseReceived();
}
コード例 #5
0
ファイル: ApplyMarkQuery.cpp プロジェクト: 4ukuta/core
void ApplyMarkQuery::onManagerFinished(QNetworkReply *reply)
{
  QByteArray jsonResponseByteArray = reply->readAll();

  if (jsonResponseByteArray.size() > 0)
  {
    QString jsonResponse(jsonResponseByteArray);
    qDebug() << "Gotten response (json): " << jsonResponse;
    QJson::Parser parser;
    bool ok;
    QVariantMap result = parser.parse(QByteArray(jsonResponse.toAscii()), &ok).toMap();
    QString status("");
    QString status_description("");
    if (!ok)
    {
      qFatal("An error occured during parsing json with response to apply mark");
    }
    else
    {
      status = result["status"].toString();
      status_description = result["status_description"].toString();
    }

    Q_EMIT responseReceived(status,status_description);
  }
}
コード例 #6
0
int StreamingAudioClient::setTypeWithPreset(StreamingAudioType type, int preset, unsigned int timeout)
{
    if (m_port < 0) return SAC_NOT_REGISTERED; // not yet registered
    if (m_type == type && m_preset == preset) return SAC_SUCCESS; // type already set

    m_responseReceived = false;
    OscMessage msg;
    msg.init("/sam/set/type", "iiii", m_port, type, preset, m_replyPort);
    if (!OscClient::sendFromSocket(&msg, &m_socket))
    {
        qWarning("StreamingAudioClient::setType() Couldn't send OSC message");
        return SAC_OSC_ERROR;
    }

    // wait on response from SAM
    QEventLoop loop;
    connect(this, SIGNAL(responseReceived()), &loop, SLOT(quit()));
    QTimer::singleShot(timeout, &loop, SLOT(quit()));
    loop.exec();

    if (!m_responseReceived)
    {
        qWarning("StreamingAudioClient::setType() timed out waiting for response to set/type request");
        return SAC_TIMEOUT;
    }

    return ((m_type == type && m_preset == preset) ? SAC_SUCCESS : SAC_REQUEST_DENIED);
}
コード例 #7
0
void StreamingAudioClient::handle_typedeny(int errorCode)
{
    qWarning("SAM type change DENIED: error code = %d", errorCode);
    // TODO: do something with the error code?
    m_responseReceived = true;
    emit responseReceived();
}
コード例 #8
0
ファイル: ntp-time.cpp プロジェクト: joscha/NtpTime
void NtpTime::run()
{
    wait();
    issueRequest();
    requestIssued();
    updateSystemTime();  //This has to be before response recieved so the timer has a chance to delay.
    responseReceived();
}
コード例 #9
0
ファイル: DocumentLoader.cpp プロジェクト: windyuuy/opera
void DocumentLoader::handleSubstituteDataLoadNow(DocumentLoaderTimer*)
{
    KURL url = m_substituteData.responseURL();
    if (url.isEmpty())
        url = m_request.url();
    ResourceResponse response(url, m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
    responseReceived(0, response);
}
コード例 #10
0
void StreamingAudioClient::handle_regdeny(int errorCode)
{
    qWarning("SAM registration DENIED: error = %d", errorCode);
   
    // check to see if we timed out
    // TODO: what if we tried re-registering after a time-out, and then received a regconfirm/regdeny??
    
    // TODO: do something with the error code?
    m_responseReceived = true;
    emit responseReceived();
}
コード例 #11
0
 void UnsubscribeChannelQuery::processReply(QNetworkReply *reply)
 {
   DefaultResponseJSON response;
   response.parseJson(reply->readAll());
   if(response.getStatus() == "Ok")
   {
     m_status="Ok";
     Q_EMIT responseReceived();
   }
   else
   {
     Q_EMIT errorOccured(response.getStatusMessage());
   }
 }
コード例 #12
0
void MainResourceLoader::handleSubstituteDataLoadNow(MainResourceLoaderTimer*)
{
    RefPtr<MainResourceLoader> protect(this);

    KURL url = m_substituteData.responseURL();
    if (url.isEmpty())
        url = m_initialRequest.url();

    // Clear the initial request here so that subsequent entries into the
    // loader will not think there's still a deferred load left to do.
    m_initialRequest = ResourceRequest();
        
    ResourceResponse response(url, m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
    responseReceived(0, response);
}
コード例 #13
0
ファイル: servatrice.cpp プロジェクト: Aurenos/Cockatrice
void Servatrice::addIslInterface(int serverId, IslInterface *interface)
{
    // Only call with islLock locked for writing
    
    islInterfaces.insert(serverId, interface);
    connect(interface, SIGNAL(externalUserJoined(ServerInfo_User)), this, SLOT(externalUserJoined(ServerInfo_User)));
    connect(interface, SIGNAL(externalUserLeft(QString)), this, SLOT(externalUserLeft(QString)));
    connect(interface, SIGNAL(externalRoomUserJoined(int, ServerInfo_User)), this, SLOT(externalRoomUserJoined(int, ServerInfo_User)));
    connect(interface, SIGNAL(externalRoomUserLeft(int, QString)), this, SLOT(externalRoomUserLeft(int, QString)));
    connect(interface, SIGNAL(externalRoomSay(int, QString, QString)), this, SLOT(externalRoomSay(int, QString, QString)));
    connect(interface, SIGNAL(externalRoomGameListChanged(int, ServerInfo_Game)), this, SLOT(externalRoomGameListChanged(int, ServerInfo_Game)));
    connect(interface, SIGNAL(joinGameCommandReceived(Command_JoinGame, int, int, int, qint64)), this, SLOT(externalJoinGameCommandReceived(Command_JoinGame, int, int, int, qint64)));
    connect(interface, SIGNAL(gameCommandContainerReceived(CommandContainer, int, int, qint64)), this, SLOT(externalGameCommandContainerReceived(CommandContainer, int, int, qint64)));
    connect(interface, SIGNAL(responseReceived(Response, qint64)), this, SLOT(externalResponseReceived(Response, qint64)));
    connect(interface, SIGNAL(gameEventContainerReceived(GameEventContainer, qint64)), this, SLOT(externalGameEventContainerReceived(GameEventContainer, qint64)));
}
コード例 #14
0
ファイル: TcpRpcChannel.cpp プロジェクト: adanselm/pbRPCpp
    void TcpRpcChannel::dataReceived(const boost::system::error_code& ec,
            std::size_t bytes_transferred) {
        if (ec) {
            GOOGLE_LOG(ERROR) << "fail to receive data from server";
            startConnect();
            return;
        }

        GOOGLE_LOG(INFO) << "received " << bytes_transferred << " bytes from server";
        receivedMsg_.append(msgBuffer_, bytes_transferred);

        startRead();

        string msg;

        while (extractMessage(msg)) {
            responseReceived(msg);
        }

    }
コード例 #15
0
ファイル: UdpRpcChannel.cpp プロジェクト: adanselm/pbRPCpp
    void UdpRpcChannel::packetReceived(const boost::system::error_code& ec, std::size_t bytes_transferred) {
        if (stop_) {
            return;
        }

        if (senderEndpoint_ != remoteEndpoint_) {
            GOOGLE_LOG(ERROR) << "received a packet not from server, discard it";
            return;
        }
        string s(msgBuffer_, bytes_transferred);

        try {
            string resp_msg;
            
            while( RpcMessage::extractNetPacket( s, resp_msg ) ) {
                responseReceived( resp_msg );
            }
        } catch (...) {

        }
        startRead();

    }
コード例 #16
0
void BytestreamParser::
parse(const unsigned char c)
{
	switch (_state) {
	// there may be either a regular character from a response string, or an
	// event starting. We can determine this information by looking at the
	// high bit. If it is set, it is an event
	case 0:
		if ((c & 0x80) == 0) {
			if (c == '\n') {
				if (!_response)
					std::cerr << "EE: BytestreamParser _response is nullptr where it should not be" << std::endl;
				else
					emit responseReceived(std::move(_response));

				_response = new QString();
				_response->reserve(64);
			}
			else
				_response->append(c);
		}
		else {
			_ev = new DVSEvent;
			_ev->id = _id;
			_ev->x = static_cast<uint16_t>(c) & 0x7F;
			_ev->y = 0;
			_ev->p = 0;
			_ev->t = 0;
			++_state;
		}
		break;

	case 1:
		_ev->p = (static_cast<uint8_t>(c) & 0x80) >> 7;
		_ev->y = static_cast<uint16_t>(c) & 0x7F;
		if (_timeformat == DVSEvent::TIMEFORMAT_0BYTES) {
			emit eventReceived(std::move(_ev));
			_ev = nullptr;
			_state = 0;
		}
		else
			++_state;
		break;

	case 2:
		if (_timeformat == DVSEvent::TIMEFORMAT_2BYTES)
			_ev->t |= static_cast<uint64_t>(c) << 8;
		else
			_ev->t |= static_cast<uint64_t>(c) << 16;
		++_state;
		break;

	case 3:
		if (_timeformat == DVSEvent::TIMEFORMAT_2BYTES) {
			_ev->t |= static_cast<uint64_t>(c);
			emit eventReceived(std::move(_ev));
			_ev = nullptr;
			_state = 0;
		}
		else {
			_ev->t |= static_cast<uint64_t>(c) << 8;
			++_state;
		}
		break;

	case 4:
		_ev->t |= static_cast<uint64_t>(c);
		emit eventReceived(std::move(_ev));
		_ev = nullptr;
		_state = 0;
		break;

	default:
		// TODO: report the error to some other function, don't just
		// print it
		// found a state that should not be there. exit
		std::cerr << "EE: BytestreamParser in unknown state. resetting" << std::endl;
		_state = 0;
		break;
	}

}
コード例 #17
0
void StreamingAudioClient::handle_regconfirm(int port, unsigned int sampleRate, unsigned int bufferSize, quint16 rtpBasePort)
{
    printf("StreamingAudioClient registration confirmed: unique id = %d, rtpBasePort = %d", port, rtpBasePort);

    m_bufferSize = bufferSize;
    m_sampleRate = sampleRate;

    // init RTP
    quint16 portOffset = port * 4;
    m_sender = new RtpSender(m_samIP, portOffset + rtpBasePort, portOffset + rtpBasePort + 3, portOffset + rtpBasePort + 1, REPORT_INTERVAL_MILLIS, sampleRate, m_channels, bufferSize, port, m_payloadType);
    if (!m_sender->init())
    {
        qWarning("StreamingAudioClient::handle_regconfirm couldn't initialize RtpSender: unregistering with SAM");
        // unregister with SAM
        OscMessage msg;
        msg.init("/sam/app/unregister", "i", port);
        if (!OscClient::sendFromSocket(&msg, &m_socket))
        {
            qWarning("Couldn't send OSC message");
        }
        return;
    }
    
    // allocate audio buffer
    m_audioOut = new float*[m_channels];
    for (unsigned int ch = 0; ch < m_channels; ch++)
    {
        m_audioOut[ch] = new float[bufferSize];
    }

    // initialize and start interface if not driving SAC sending externally
    if (!m_driveExternally)
    {
#ifdef SAC_NO_JACK
        m_interface = new VirtualAudioInterface(m_channels, bufferSize, sampleRate);
#else
        // write the JACK client name
        char clientName[MAX_CLIENT_NAME];
        snprintf(clientName, MAX_CLIENT_NAME, "SAC-client%d-%d", rtpBasePort, port);
    
        m_interface = new JackAudioInterface(m_channels, bufferSize, sampleRate, clientName);
#endif
        m_interface->setAudioCallback(StreamingAudioClient::interface_callback, this);

        // start interface (start sending audio)
        if (!m_interface->go())
        {
            qWarning("StreamingAudioClient::handle_regconfirm ERROR: couldn't start audio interface : unregistering with SAM");
            // unregister with SAM
            OscMessage msg;
            msg.init("/sam/app/unregister", "i", port);
            if (!OscClient::sendFromSocket(&msg, &m_socket))
            {
                qWarning("Couldn't send OSC message");
            }
            return;
        }
    }

    m_port = port;
    m_responseReceived = true;
    emit responseReceived();
}
コード例 #18
0
// In this method, we can clear |request| to tell content::WebURLLoaderImpl of
// Chromium not to follow the redirect. This works only when this method is
// called by RawResource::willSendRequest(). If called by
// RawResource::didAddClient(), clearing |request| won't be propagated
// to content::WebURLLoaderImpl. So, this loader must also get detached from
// the resource by calling clearResource().
void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse)
{
    ASSERT(m_client);
    ASSERT_UNUSED(resource, resource == this->resource());
    ASSERT(m_async);

    if (!m_actualRequest.isNull()) {
        reportResponseReceived(resource->identifier(), redirectResponse);

        handlePreflightFailure(redirectResponse.url().string(), "Response for preflight is invalid (redirect)");
        // |this| may be dead here.

        request = ResourceRequest();

        return;
    }

    if (m_redirectMode == WebURLRequest::FetchRedirectModeManual) {
        // Keep |this| alive even if the client release a reference in
        // responseReceived().
        RefPtr<DocumentThreadableLoader> protect(this);

        // We use |m_redirectMode| to check the original redirect mode.
        // |request| is a new request for redirect. So we don't set the redirect
        // mode of it in WebURLLoaderImpl::Context::OnReceivedRedirect().
        ASSERT(request.useStreamOnResponse());
        // There is no need to read the body of redirect response because there
        // is no way to read the body of opaque-redirect filtered response's
        // internal response.
        // TODO(horo): If we support any API which expose the internal body, we
        // will have to read the body. And also HTTPCache changes will be needed
        // because it doesn't store the body of redirect responses.
        responseReceived(resource, redirectResponse, adoptPtr(new EmptyDataHandle()));

        if (m_client) {
            ASSERT(m_actualRequest.isNull());
            notifyFinished(resource);
        }

        request = ResourceRequest();

        return;
    }

    if (m_redirectMode == WebURLRequest::FetchRedirectModeError || !isAllowedByContentSecurityPolicy(request.url(), ContentSecurityPolicy::DidRedirect)) {
        ThreadableLoaderClient* client = m_client;
        clear();
        client->didFailRedirectCheck();
        // |this| may be dead here.

        request = ResourceRequest();

        return;
    }

    // Allow same origin requests to continue after allowing clients to audit the redirect.
    if (isAllowedRedirect(request.url())) {
        if (m_client->isDocumentThreadableLoaderClient())
            static_cast<DocumentThreadableLoaderClient*>(m_client)->willFollowRedirect(request, redirectResponse);
        return;
    }

    if (m_corsRedirectLimit <= 0) {
        ThreadableLoaderClient* client = m_client;
        clear();
        client->didFailRedirectCheck();
        // |this| may be dead here.
    } else if (m_options.crossOriginRequestPolicy == UseAccessControl) {
        --m_corsRedirectLimit;

        InspectorInstrumentation::didReceiveCORSRedirectResponse(document().frame(), resource->identifier(), document().frame()->loader().documentLoader(), redirectResponse, 0);

        bool allowRedirect = false;
        String accessControlErrorDescription;

        // Non-simple cross origin requests (both preflight and actual one) are
        // not allowed to follow redirect.
        if (m_crossOriginNonSimpleRequest) {
            accessControlErrorDescription = "The request was redirected to '"+ request.url().string() + "', which is disallowed for cross-origin requests that require preflight.";
        } else {
            // The redirect response must pass the access control check if the
            // original request was not same-origin.
            allowRedirect = CrossOriginAccessControl::isLegalRedirectLocation(request.url(), accessControlErrorDescription)
                && (m_sameOriginRequest || passesAccessControlCheck(redirectResponse, effectiveAllowCredentials(), securityOrigin(), accessControlErrorDescription, m_requestContext));
        }

        if (allowRedirect) {
            // FIXME: consider combining this with CORS redirect handling performed by
            // CrossOriginAccessControl::handleRedirect().
            clearResource();

            RefPtr<SecurityOrigin> originalOrigin = SecurityOrigin::create(redirectResponse.url());
            RefPtr<SecurityOrigin> requestOrigin = SecurityOrigin::create(request.url());
            // If the original request wasn't same-origin, then if the request URL origin is not same origin with the original URL origin,
            // set the source origin to a globally unique identifier. (If the original request was same-origin, the origin of the new request
            // should be the original URL origin.)
            if (!m_sameOriginRequest && !originalOrigin->isSameSchemeHostPort(requestOrigin.get()))
                m_securityOrigin = SecurityOrigin::createUnique();
            // Force any subsequent requests to use these checks.
            m_sameOriginRequest = false;

            // Since the request is no longer same-origin, if the user didn't request credentials in
            // the first place, update our state so we neither request them nor expect they must be allowed.
            if (m_resourceLoaderOptions.credentialsRequested == ClientDidNotRequestCredentials)
                m_forceDoNotAllowStoredCredentials = true;

            // Remove any headers that may have been added by the network layer that cause access control to fail.
            request.clearHTTPReferrer();
            request.clearHTTPOrigin();
            request.clearHTTPUserAgent();
            // Add any CORS simple request headers which we previously saved from the original request.
            for (const auto& header : m_simpleRequestHeaders)
                request.setHTTPHeaderField(header.key, header.value);
            makeCrossOriginAccessRequest(request);
            // |this| may be dead here.
            return;
        }

        ThreadableLoaderClient* client = m_client;
        clear();
        client->didFailAccessControlCheck(ResourceError(errorDomainBlinkInternal, 0, redirectResponse.url().string(), accessControlErrorDescription));
        // |this| may be dead here.
    } else {
        ThreadableLoaderClient* client = m_client;
        clear();
        client->didFailRedirectCheck();
        // |this| may be dead here.
    }

    request = ResourceRequest();
}
コード例 #19
0
int StreamingAudioClient::start(int x, int y, int width, int height, int depth, unsigned int timeout)
{
    if (m_port >= 0) return SAC_ERROR; // already registered
    if (!m_samIP) return SAC_ERROR; // not initialized yet
    
    printf("\n");
    printf("--------------------------------------\n");
    printf("Streaming Audio Client version %d.%d.%d\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
    printf("Built on %s at %s\n", __DATE__, __TIME__);
    printf("Copyright UCSD 2011-2013\n");
    printf("Connecting to SAM at IP %s, port %d\n", m_samIP, m_samPort);
    printf("--------------------------------------\n\n");
    
    // bind to local IP and port (Qt 5+ only)
    if (m_replyIP || m_replyPort > 0)
    {
#if QT_VERSION >= 0x050000
        if (m_replyIP)
        {
            QString replyIPStr(m_replyIP);
            QHostAddress replyIPAddr(replyIPStr);
            m_socket.bind(replyIPAddr, m_replyPort);
        }
        else
        {
            m_socket.bind(QHostAddress::Any, m_replyPort);
        }
#else
        qWarning("Couldn't bind to specified local IP and port.  Qt version 5.0+ required.");
        return SAC_ERROR;
#endif
    }

    QString samIPStr(m_samIP);
    m_socket.connectToHost(samIPStr, m_samPort);
    if (!m_socket.waitForConnected(timeout))
    {
        qWarning("StreamingAudioClient::start() couldn't connect to SAM");
        return SAC_TIMEOUT;
    }
    
    m_replyPort = m_socket.localPort();

    // set up listening for OSC messages
    m_oscReader = new OscTcpSocketReader(&m_socket);
    connect(&m_socket, SIGNAL(readyRead()), m_oscReader, SLOT(readFromSocket()));
    connect(m_oscReader, SIGNAL(messageReady(OscMessage*, const char*, QAbstractSocket*)), this, SLOT(handleOscMessage(OscMessage*, const char*, QAbstractSocket*)));
    connect(&m_socket, SIGNAL(disconnected()), this, SLOT(samDisconnected()));
    
    OscMessage msg;
    msg.init("/sam/app/register", "siiiiiiiiiiiiii", m_name, m_channels,
                                                       x,
                                                       y,
                                                       width,
                                                       height,
                                                       depth,
                                                       m_type,
                                                       m_preset,
                                                       0, // placeholder for packet size/samples per packet requested
                                                       m_packetQueueSize,
                                                       VERSION_MAJOR,
                                                       VERSION_MINOR,
                                                       VERSION_PATCH,
                                                       m_replyPort);
    if (!OscClient::sendFromSocket(&msg, &m_socket))
    {
        qWarning("StreamingAudioClient::start() Couldn't send OSC message");
        return SAC_OSC_ERROR;
    }

    // wait on response from SAM
    QEventLoop loop;
    connect(this, SIGNAL(responseReceived()), &loop, SLOT(quit()));
    QTimer::singleShot(timeout, &loop, SLOT(quit()));
    loop.exec();

    if (!m_responseReceived)
    {
        qWarning("StreamingAudioClient::start() timed out waiting for response to register request");
        return SAC_TIMEOUT;
    }
    else if (m_port < 0)
    {
       return SAC_REQUEST_DENIED;
    }

    return SAC_SUCCESS;
}
コード例 #20
0
ファイル: ProfilerThread.cpp プロジェクト: 4ukuta/core
void ProfilerThread::setConnections()
{
  connect(this,SIGNAL(doRequest()),this, SLOT(sendRequest()));
  connect(m_query,SIGNAL(errorOccured(int)),this, SLOT(responseReceived()));
  connect(m_query,SIGNAL(success()),this, SLOT(responseReceived()));
}
コード例 #21
0
ファイル: multipointcom.cpp プロジェクト: xlongfeng/skynet
void MultiPointCom::run()
{
    mutex.lock();

    QTime timeout = lastConnectTime.addSecs(30);

    if (timeout < QTime::currentTime()) {
        qDebug() << "Device connected timeout" << disconnectCount++;
        lastConnectTime = QTime::currentTime();
#ifdef __arm__
        ioctl(device, SI4432_IOC_RESET, 1);
#endif
    }

#ifdef __arm__
    si4432_ioc_transfer tr;
    char txBuf[64], rxBuf[64];
    memcpy(txBuf, request.data(), request.size());
    memset(&tr, 0, sizeof(si4432_ioc_transfer));
    tr.tx_buf = (__u64)txBuf;
    tr.rx_buf = (__u64)rxBuf;
    tr.len = request.size();
    int len = ioctl(device, SI4432_IOC_MESSAGE(1), &tr);
    if (len > 0) {
        response.clear();
        response.append(rxBuf, len);
        quint8 addr = response.at(0);
        if (addr == address) {
            lastConnectTime = QTime::currentTime();
            disconnect = 0;
            emit deviceConnected();
            emit responseReceived(response.at(1), QByteArray(response.data() + 2, len - 2));
        }
    } else {
        disconnect++;
        if (disconnect > 3) {
            disconnect = 0;
            emit deviceDisconnected();
        }
    }
#else
    QUdpSocket *udp = new QUdpSocket();
    udp->writeDatagram(request, QHostAddress::LocalHost, 19999);

    if (udp->waitForReadyRead(100) && (udp->pendingDatagramSize() > 0)) {
        response.resize(udp->pendingDatagramSize());
        udp->readDatagram(response.data(), response.size());
        quint8 addr = response.at(0);
        if (addr == address) {
            lastConnectTime = QTime::currentTime();
            disconnect = 0;
            emit deviceConnected();
            emit responseReceived(response.at(1), response.mid(2));
        }
    } else {
        disconnect++;
        if (disconnect > 3) {
            disconnect = 0;
            emit deviceDisconnected();
        }
    }
    delete udp;
#endif

    mutex.unlock();
}
コード例 #22
0
// In this method, we can clear |request| to tell content::WebURLLoaderImpl of
// Chromium not to follow the redirect. This works only when this method is
// called by RawResource::willSendRequest(). If called by
// RawResource::didAddClient(), clearing |request| won't be propagated to
// content::WebURLLoaderImpl. So, this loader must also get detached from the
// resource by calling clearResource().
bool DocumentThreadableLoader::redirectReceived(
    Resource* resource,
    const ResourceRequest& request,
    const ResourceResponse& redirectResponse) {
  DCHECK(m_client);
  DCHECK_EQ(resource, this->resource());
  DCHECK(m_async);

  m_checker.redirectReceived();

  if (!m_actualRequest.isNull()) {
    reportResponseReceived(resource->identifier(), redirectResponse);

    handlePreflightFailure(redirectResponse.url().getString(),
                           "Response for preflight is invalid (redirect)");

    return false;
  }

  if (m_redirectMode == WebURLRequest::FetchRedirectModeManual) {
    // We use |m_redirectMode| to check the original redirect mode. |request| is
    // a new request for redirect. So we don't set the redirect mode of it in
    // WebURLLoaderImpl::Context::OnReceivedRedirect().
    DCHECK(request.useStreamOnResponse());
    // There is no need to read the body of redirect response because there is
    // no way to read the body of opaque-redirect filtered response's internal
    // response.
    // TODO(horo): If we support any API which expose the internal body, we will
    // have to read the body. And also HTTPCache changes will be needed because
    // it doesn't store the body of redirect responses.
    responseReceived(resource, redirectResponse,
                     WTF::makeUnique<EmptyDataHandle>());

    if (m_client) {
      DCHECK(m_actualRequest.isNull());
      notifyFinished(resource);
    }

    return false;
  }

  if (m_redirectMode == WebURLRequest::FetchRedirectModeError) {
    ThreadableLoaderClient* client = m_client;
    clear();
    client->didFailRedirectCheck();

    return false;
  }

  // Allow same origin requests to continue after allowing clients to audit the
  // redirect.
  if (isAllowedRedirect(request.url())) {
    m_client->didReceiveRedirectTo(request.url());
    if (m_client->isDocumentThreadableLoaderClient()) {
      return static_cast<DocumentThreadableLoaderClient*>(m_client)
          ->willFollowRedirect(request, redirectResponse);
    }
    return true;
  }

  if (m_corsRedirectLimit <= 0) {
    ThreadableLoaderClient* client = m_client;
    clear();
    client->didFailRedirectCheck();
    return false;
  }

  --m_corsRedirectLimit;

  InspectorInstrumentation::didReceiveCORSRedirectResponse(
      document().frame(), resource->identifier(),
      document().frame()->loader().documentLoader(), redirectResponse,
      resource);

  bool allowRedirect = false;
  String accessControlErrorDescription;

  if (!CrossOriginAccessControl::isLegalRedirectLocation(
          request.url(), accessControlErrorDescription)) {
    accessControlErrorDescription =
        "Redirect from '" + redirectResponse.url().getString() +
        "' has been blocked by CORS policy: " + accessControlErrorDescription;
  } else if (!m_sameOriginRequest &&
             !passesAccessControlCheck(
                 redirectResponse, effectiveAllowCredentials(),
                 getSecurityOrigin(), accessControlErrorDescription,
                 m_requestContext)) {
    // The redirect response must pass the access control check if the original
    // request was not same-origin.
    accessControlErrorDescription =
        "Redirect from '" + redirectResponse.url().getString() + "' to '" +
        request.url().getString() + "' has been blocked by CORS policy: " +
        accessControlErrorDescription;
  } else {
    allowRedirect = true;
  }

  if (!allowRedirect) {
    ThreadableLoaderClient* client = m_client;
    clear();
    client->didFailAccessControlCheck(ResourceError(
        errorDomainBlinkInternal, 0, redirectResponse.url().getString(),
        accessControlErrorDescription));
    return false;
  }

  m_client->didReceiveRedirectTo(request.url());

  // FIXME: consider combining this with CORS redirect handling performed by
  // CrossOriginAccessControl::handleRedirect().
  clearResource();

  // If the original request wasn't same-origin, then if the request URL origin
  // is not same origin with the original URL origin, set the source origin to a
  // globally unique identifier. (If the original request was same-origin, the
  // origin of the new request should be the original URL origin.)
  if (!m_sameOriginRequest) {
    RefPtr<SecurityOrigin> originalOrigin =
        SecurityOrigin::create(redirectResponse.url());
    RefPtr<SecurityOrigin> requestOrigin =
        SecurityOrigin::create(request.url());
    if (!originalOrigin->isSameSchemeHostPort(requestOrigin.get()))
      m_securityOrigin = SecurityOrigin::createUnique();
  }
  // Force any subsequent requests to use these checks.
  m_sameOriginRequest = false;

  // Since the request is no longer same-origin, if the user didn't request
  // credentials in the first place, update our state so we neither request them
  // nor expect they must be allowed.
  if (m_resourceLoaderOptions.credentialsRequested ==
      ClientDidNotRequestCredentials)
    m_forceDoNotAllowStoredCredentials = true;

  // Save the referrer to use when following the redirect.
  m_overrideReferrer = true;
  m_referrerAfterRedirect =
      Referrer(request.httpReferrer(), request.getReferrerPolicy());

  ResourceRequest crossOriginRequest(request);

  // Remove any headers that may have been added by the network layer that cause
  // access control to fail.
  crossOriginRequest.clearHTTPReferrer();
  crossOriginRequest.clearHTTPOrigin();
  crossOriginRequest.clearHTTPUserAgent();
  // Add any request headers which we previously saved from the
  // original request.
  for (const auto& header : m_requestHeaders)
    crossOriginRequest.setHTTPHeaderField(header.key, header.value);
  makeCrossOriginAccessRequest(crossOriginRequest);

  return false;
}
コード例 #23
0
ファイル: JsonRpc.cpp プロジェクト: Eyepea/xivo-gallifrey
	void JsonRpc::processJson(const QString& json)
	{
		QList<QVariantMap> objects;
		try
		{
			objects = JsonToVariant::multiParse(json);
		}
		catch(ParseException)
		{
			sendError(QVariant(), InvalidJson, "Parse error.");
			return;
		}
		Q_FOREACH(const QVariantMap& object, objects)
		{
			if(object.value("jsonrpc").toString() != "2.0")
			{
				sendError(object.value("id"), InvalidJsonRpc, "JSON-RPC version not specified or not supported.", object);
				continue;
			}

			// Notification or request
			if(object.contains("method"))
			{
				if(object.value("method").type() != QVariant::String)
				{
					sendError(object.value("id"), InvalidJsonRpc, "'method' member of request must be a string.", object);
					continue;
				}
				QString method = object.value("method").toString();

				QVariant parameters = object.value("params");

				if(parameters.isNull()) parameters = QVariantList();
				if(parameters.type() != QVariant::List && parameters.type() != QVariant::Map)
				{
					sendError(object.value("id"), InvalidJsonRpc, "'parameters' member of request must be omitted, a list, or an object.", object);
					continue;
				}

				// Request or notification
				if(object.contains("id"))
				{
					emit requestReceived(object.value("id"), method, parameters);
				}
				else
				{
					emit notificationReceived(method, parameters);
				}
				continue;
			}

			// Request successful
			if(object.contains("result"))
			{
				if(!object.contains("id"))
				{
					sendError(QVariant(), InvalidJsonRpc, "ID not specified in response.", object);
					continue;
				}

				emit responseReceived(object.value("id"), object.value("result"));
				continue;
			}

			// Request failed
			if(object.contains("error"))
			{
				if(!object.contains("id"))
				{
					sendError(QVariant(), InvalidJsonRpc, "ID not specified in response.", object);
					continue;
				}

				if(object.value("error").type() != QVariant::Map)
				{
					sendError(object.value("id"), InvalidJsonRpc, "'error' member is not an Error object.", object);
					continue;
				}

				QVariantMap error = object.value("error").toMap();
				if(error.value("code").type() != QVariant::Int)
				{
					sendError(object.value("id"), InvalidJsonRpc, "'code' member of error object is not an integer.", object);
					continue;
				}

				if(error.value("message").type() != QVariant::String)
				{
					sendError(object.value("id"), InvalidJsonRpc, "'message' member of error object is not a string.", object);
					continue;
				}

				emit errorReceived(object.value("id"), error.value("code").toInt(), error.value("message").toString(), error.value("data"));
				continue;
			}

			// Not a notification, request, or response
			sendError(object.value("id"), InvalidJsonRpc, "JSON object doesn't appear to be a JSON-RPC request, notification, or response.", object);
		}
	}