Пример #1
0
    void
    RTMPSession::streamStatusChanged(StreamStatus_t status)
    {
        if(status & kStreamStatusConnected && m_state < kClientStateConnected) {
            setClientState(kClientStateConnected);
        }
        if(status & kStreamStatusReadBufferHasBytes) {
            dataReceived();
        }
        if(status & kStreamStatusWriteBufferHasSpace) {
            if(m_state < kClientStateHandshakeComplete) {
                handshake();
            } else {
                
#ifdef __APPLE__
                dispatch_semaphore_signal(m_networkWaitSemaphore);
#else 
                m_networkMutex.unlock();
                m_networkCond.notify_one();
#endif
            }
        }
        if(status & kStreamStatusEndStream) {
            setClientState(kClientStateNotConnected);
        }
        if(status & kStreamStatusErrorEncountered) {
            setClientState(kClientStateError);
        }
    }
Пример #2
0
 void
 RTMPSession::streamStatusChanged(StreamStatus_t status)
 {
     if(status & kStreamStatusConnected && m_state < kClientStateConnected) {
         setClientState(kClientStateConnected);
     }
     if(status & kStreamStatusReadBufferHasBytes) {
         dataReceived();
     }
     if(status & kStreamStatusWriteBufferHasSpace) {
         if(m_state < kClientStateHandshakeComplete) {
             handshake();
         } else if (!m_ending) {
             m_jobQueue.enqueue([this]() {
                 this->write(nullptr, 0);
             });
         }
     }
     if(status & kStreamStatusEndStream) {
         setClientState(kClientStateNotConnected);
     }
     if(status & kStreamStatusErrorEncountered) {
         setClientState(kClientStateError);
     }
 }
Пример #3
0
 void
 RTMPSession::handleInvoke(uint8_t* p)
 {
     int buflen=0;
     std::string command = get_string(p, buflen);
     int32_t pktId = int32_t(get_double(p+11));
     
     DLog("pktId: %d\n", pktId);
     std::string trackedCommand ;
     auto it = m_trackedCommands.find(pktId) ;
     
     if(it != m_trackedCommands.end()) {
         trackedCommand = it->second;
     }
     
     DLog("received invoke %s\n", command.c_str());
     
     if (command == "_result") {
         DLog("tracked command: %s\n", trackedCommand.c_str());
         if (trackedCommand == "connect") {
             
             sendReleaseStream();
             sendFCPublish();
             sendCreateStream();
             setClientState(kClientStateFCPublish);
             
         } else if (trackedCommand == "createStream") {
             if (p[10] || p[19] != 0x05 || p[20]) {
                 DLog("RTMP: Unexpected reply on connect()\n");
             } else {
                 m_streamId = get_double(p+21);
             }
             sendPublish();
             setClientState(kClientStateReady);
         }
     } else if (command == "onStatus") {
         std::string code = parseStatusCode(p + 3 + command.length());
         DLog("code : %s\n", code.c_str());
         if (code == "NetStream.Publish.Start") {
             
             sendHeaderPacket();
             
             sendSetChunkSize(getpagesize());
             // sendSetBufferTime(0);
             setClientState(kClientStateSessionStarted);
             
             m_throughputSession.start();
         }
     }
     
 }
Пример #4
0
ConfigurationTransport::ConfigurationTransport(IKaaChannelManager& channelManager, IKaaClientStateStoragePtr status)
    : AbstractKaaTransport(channelManager)
    , configurationProcessor_(nullptr)
    , hashContainer_(nullptr)
{
    setClientState(status);
}
Пример #5
0
UA_StatusCode
UA_Client_connect_iterate(UA_Client *client) {
    UA_LOG_TRACE(&client->config.logger, UA_LOGCATEGORY_CLIENT,
                 "Client connect iterate");
    if (client->connection.state == UA_CONNECTION_ESTABLISHED){
        if(client->state < UA_CLIENTSTATE_WAITING_FOR_ACK) {
            client->connectStatus = sendHELMessage(client);
            if(client->connectStatus == UA_STATUSCODE_GOOD) {
                setClientState(client, UA_CLIENTSTATE_WAITING_FOR_ACK);
            } else {
                client->connection.close(&client->connection);
                client->connection.free(&client->connection);
            }
            return client->connectStatus;
        }
    }

    /* If server is not connected */
    if(client->connection.state == UA_CONNECTION_CLOSED) {
        client->connectStatus = UA_STATUSCODE_BADCONNECTIONCLOSED;
        UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_NETWORK,
                     "No connection to server.");
    }

    if(client->connectStatus != UA_STATUSCODE_GOOD) {
        client->connection.close(&client->connection);
        client->connection.free(&client->connection);
    }

    return client->connectStatus;
}
Пример #6
0
void Client::iconify()
{
	qDebug() << "ICONIFY";
	unmap();
	setClientState(IconicState);
	dock->addClient(this);  // add to dockbar
}
Пример #7
0
void Client::map()
{
	qDebug() << "CLIENT MAP";
	XUngrabKeyboard(display(), CurrentTime);
	show();
	XMapWindow(display(), clientId);
	setClientState(NormalState);
	XGrabKeyboard(display(), clientId, TRUE, GrabModeAsync, GrabModeAsync, CurrentTime);
}
Пример #8
0
NotificationTransport::NotificationTransport(IKaaClientStateStoragePtr status, IKaaChannelManager& manager)
    : AbstractKaaTransport(manager), notificationProcessor_(nullptr)
{
    setClientState(status);

    const DetailedTopicStates& detailedStatesContainer = clientStatus_->getTopicStates();
    for (const auto& state : detailedStatesContainer) {
        notificationSubscriptions_.insert(std::make_pair(state.second.topicId, state.second.sequenceNumber));
    }
}
Пример #9
0
 void
 RTMPSession::handshake0()
 {
     char c0 = 0x03;
     
     setClientState(kClientStateHandshake0);
     
     write((uint8_t*)&c0, 1);
     
     handshake();
 }
Пример #10
0
void STATE_APIENTRY crStateDisableClientState (GLenum array) 
{
	CRContext *g = GetCurrentContext();
	CRClientState *c = &(g->client);
	CRStateBits *sb = GetCurrentBits();
	CRClientBits *cb = &(sb->client);

	FLUSH();

	setClientState(c, cb, g->neg_bitid, array, GL_FALSE);
}
Пример #11
0
 void
 RTMPSession::handshake2()
 {
     setClientState(kClientStateHandshake2);
     uint8_t* p;
     m_s1.read(&p, kRTMPSignatureSize);
     p += 4;
     uint32_t zero = 0;
     memcpy(p, &zero, sizeof(uint32_t));
     
     write(m_s1(), m_s1.size());
 }
Пример #12
0
 void
 RTMPSession::handshake1()
 {
     setClientState(kClientStateHandshake1s0);
     
     m_c1.resize(kRTMPSignatureSize);
     uint8_t* p;
     m_c1.read(&p, kRTMPSignatureSize);
     uint64_t zero = 0;
     m_c1.put((uint8_t*)&zero, sizeof(uint64_t));
     
     write(p, kRTMPSignatureSize);
     
 }
Пример #13
0
void Client::getWMHints()
{
	XWMHints *xwmhints;
	if ((xwmhints = XGetWMHints(display(), clientId)) != NULL) {
		if (xwmhints->flags & StateHint && xwmhints->initial_state == IconicState) {
			setClientState(IconicState);
		}
		if (xwmhints->flags & IconPixmapHint) {
			getServerIcon(xwmhints->icon_pixmap, (xwmhints->flags & IconMaskHint)?(xwmhints->icon_mask):(None));
		}
		if (appIcon.isNull())
			appIcon = QPixmap(":/default/appicon.png");
		// FIXME: UrgencyHint not defined
		//Urgency = xwmhints->flags & UrgencyHint;
		wantFocus = xwmhints->input;
		XFree(xwmhints);
    }
}
Пример #14
0
UA_StatusCode
UA_Client_disconnect_async(UA_Client *client, UA_UInt32 *requestId) {
    /* Is a session established? */
    if (client->state == UA_CLIENTSTATE_SESSION) {
        client->state = UA_CLIENTSTATE_SESSION_DISCONNECTED;
        sendCloseSessionAsync(client, requestId);
    }

    /* Close the TCP connection
     * shutdown and close (in tcp.c) are already async*/
    if (client->state >= UA_CLIENTSTATE_CONNECTED)
        client->connection.close(&client->connection);
    else
        UA_Client_removeRepeatedCallback(client, client->connection.connectCallbackID);

#ifdef UA_ENABLE_SUBSCRIPTIONS
// TODO REMOVE WHEN UA_SESSION_RECOVERY IS READY
    /* We need to clean up the subscriptions */
    UA_Client_Subscriptions_clean(client);
#endif

    setClientState(client, UA_CLIENTSTATE_DISCONNECTED);
    return UA_STATUSCODE_GOOD;
}
Пример #15
0
static void
responseActivateSession(UA_Client *client, void *userdata, UA_UInt32 requestId,
                        void *response) {
    UA_ActivateSessionResponse *activateResponse =
            (UA_ActivateSessionResponse *) response;
    if(activateResponse->responseHeader.serviceResult) {
        UA_LOG_ERROR(&client->config.logger, UA_LOGCATEGORY_CLIENT,
                     "ActivateSession failed with error code %s",
                     UA_StatusCode_name(activateResponse->responseHeader.serviceResult));
    }
    client->connection.state = UA_CONNECTION_ESTABLISHED;
    setClientState(client, UA_CLIENTSTATE_SESSION);

#ifdef UA_ENABLE_SUBSCRIPTIONS
    /* A new session has been created. We need to clean up the subscriptions */
    UA_Client_Subscriptions_clean(client);
#endif

     /* Call onConnect (client_async.c) callback */
    if(client->asyncConnectCall.callback)
        client->asyncConnectCall.callback(client, client->asyncConnectCall.userdata,
                                          requestId + 1,
                                          &activateResponse->responseHeader.serviceResult);
}
Пример #16
0
 void
 RTMPSession::dataReceived()
 {
     
     static uint8_t buffer[4096] = {0};
     bool stop1 = false;
     bool stop2 = false;
     do {
         
         size_t maxlen = m_streamInBuffer->total() - m_streamInBuffer->size();
         size_t len = m_streamSession->read(buffer, maxlen);
         
         m_streamInBuffer->put(&buffer[0], len);
         
         while(m_streamInBuffer->size() > 0 && !stop1) {
             
             switch(m_state) {
                 case kClientStateHandshake1s0:
                 {
                     uint8_t s0 ;
                     m_streamInBuffer->get(&s0, 1);
                     
                     if(s0 == 0x03) {
                         setClientState(kClientStateHandshake1s1);
                     }
                 }
                     break;
                     
                 case kClientStateHandshake1s1:
                 {
                     if(m_streamInBuffer->size() >= kRTMPSignatureSize) {
                         
                         uint8_t buf[kRTMPSignatureSize];
                         size_t size = m_streamInBuffer->get(buf, kRTMPSignatureSize);
                         m_s1.resize(size);
                         m_s1.put(buf, size);
                         handshake();
                     } else {
                         stop1 = true;
                     }
                 }
                     break;
                 case kClientStateHandshake2:
                 {
                     if(m_streamInBuffer->size() >= kRTMPSignatureSize) {
                         uint8_t buf[kRTMPSignatureSize];
                         m_streamInBuffer->get(buf, kRTMPSignatureSize);
                         
                         setClientState(kClientStateHandshakeComplete);
                         handshake();
                         sendConnectPacket();
                     } else {
                         stop1 = true;
                     }
                 }
                     break;
                 default:
                 {
                     if(!parseCurrentData()) {
                         // the buffer seems corrupted.
                         stop1 = stop2 = true;
                     }
                 }
             }
         }
         
     } while((m_streamSession->status() & kStreamStatusReadBufferHasBytes) && !stop2);
 }
Пример #17
0
static void
processDecodedOPNResponseAsync(void *application, UA_SecureChannel *channel,
                                UA_MessageType messageType,
                                UA_UInt32 requestId,
                                const UA_ByteString *message) {
    /* Does the request id match? */
    UA_Client *client = (UA_Client*)application;
    if(requestId != client->requestId) {
        UA_Client_disconnect(client);
        return;
    }

    /* Is the content of the expected type? */
    size_t offset = 0;
    UA_NodeId responseId;
    UA_NodeId expectedId = UA_NODEID_NUMERIC(
            0, UA_TYPES[UA_TYPES_OPENSECURECHANNELRESPONSE].binaryEncodingId);
    UA_StatusCode retval = UA_NodeId_decodeBinary(message, &offset,
                                                  &responseId);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_Client_disconnect(client);
        return;
    }
    if(!UA_NodeId_equal(&responseId, &expectedId)) {
        UA_NodeId_deleteMembers(&responseId);
        UA_Client_disconnect(client);
        return;
    }
    UA_NodeId_deleteMembers (&responseId);

    /* Decode the response */
    UA_OpenSecureChannelResponse response;
    retval = UA_OpenSecureChannelResponse_decodeBinary(message, &offset,
                                                       &response);
    if(retval != UA_STATUSCODE_GOOD) {
        UA_Client_disconnect(client);
        return;
    }

    /* Response.securityToken.revisedLifetime is UInt32 we need to cast it to
     * DateTime=Int64 we take 75% of lifetime to start renewing as described in
     * standard */
    client->nextChannelRenewal = UA_DateTime_nowMonotonic()
            + (UA_DateTime) (response.securityToken.revisedLifetime
                    * (UA_Double) UA_DATETIME_MSEC * 0.75);

    /* Replace the token and nonce */
    UA_ChannelSecurityToken_deleteMembers(&client->channel.securityToken);
    UA_ByteString_deleteMembers(&client->channel.remoteNonce);
    client->channel.securityToken = response.securityToken;
    client->channel.remoteNonce = response.serverNonce;
    UA_ResponseHeader_deleteMembers(&response.responseHeader); /* the other members were moved */
    if(client->channel.state == UA_SECURECHANNELSTATE_OPEN)
        UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel renewed");
    else
        UA_LOG_DEBUG(&client->config.logger, UA_LOGCATEGORY_SECURECHANNEL, "SecureChannel opened");
    client->channel.state = UA_SECURECHANNELSTATE_OPEN;

    if(client->state < UA_CLIENTSTATE_SECURECHANNEL)
        setClientState(client, UA_CLIENTSTATE_SECURECHANNEL);
}
Пример #18
0
void RfbClient::execute()
{
  // Initialized by default message that will be logged on normal way
  // of disconnection.
  StringStorage peerStr;
  getPeerHost(&peerStr);
  StringStorage sysLogMessage;
  sysLogMessage.format(_T("The client %s has disconnected"),
                       peerStr.getString());

  ServerConfig *config = Configurator::getInstance()->getServerConfig();

  WindowsEvent connClosingEvent;

  SocketStream sockStream(m_socket);

  RfbOutputGate output(&sockStream);
  RfbInputGate input(&sockStream);

  FileTransferRequestHandler *fileTransfer = 0;

  RfbInitializer rfbInitializer(&sockStream, m_extAuthListener, this,
                                !m_isOutgoing);

  try {
    // First initialization phase
    try {
      m_log->info(_T("Entering RFB initialization phase 1"));
      rfbInitializer.authPhase();
      setClientState(IN_AUTH);
      m_log->debug(_T("RFB initialization phase 1 completed"));

      m_shared = rfbInitializer.getSharedFlag();
      m_log->debug(_T("Shared flag = %d"), (int)m_shared);
      m_viewOnlyAuth = rfbInitializer.getViewOnlyAuth();
      m_log->debug(_T("Initial view-only state = %d"), (int)m_viewOnly);
      m_log->debug(_T("Authenticated with view-only password = %d"), (int)m_viewOnlyAuth);
      m_viewOnly = m_viewOnly || m_viewOnlyAuth;

      // Let RfbClientManager handle new authenticated connection.
      m_desktop = m_extAuthListener->onClientAuth(this);

      m_log->info(_T("View only = %d"), (int)m_viewOnly);
    } catch (Exception &e) {
      m_log->error(_T("Error during RFB initialization: %s"), e.getMessage());
      throw;
    }
    _ASSERT(m_desktop != 0);

    m_constViewPort.initDesktopInterface(m_desktop);
    m_dynamicViewPort.initDesktopInterface(m_desktop);

    RfbDispatcher dispatcher(&input, &connClosingEvent);
    m_log->debug(_T("Dispatcher has been created"));
    CapContainer srvToClCaps, clToSrvCaps, encCaps;
    RfbCodeRegistrator codeRegtor(&dispatcher, &srvToClCaps, &clToSrvCaps,
                                  &encCaps);
    // Init modules
    // UpdateSender initialization
    m_updateSender = new UpdateSender(&codeRegtor, m_desktop, this,
                                      &output, m_id, m_desktop, m_log);
    m_log->debug(_T("UpdateSender has been created"));
    PixelFormat pf;
    Dimension fbDim;
    m_desktop->getFrameBufferProperties(&fbDim, &pf);
    Rect viewPort = getViewPortRect(&fbDim);
    m_updateSender->init(&Dimension(&viewPort), &pf);
    m_log->debug(_T("UpdateSender has been initialized"));
    // ClientInputHandler initialization
    m_clientInputHandler = new ClientInputHandler(&codeRegtor, this,
                                                  m_viewOnly);
    m_log->debug(_T("ClientInputHandler has been created"));
    // ClipboardExchange initialization
    m_clipboardExchange = new ClipboardExchange(&codeRegtor, m_desktop, &output,
                                                m_viewOnly, m_log);
    m_log->debug(_T("ClipboardExchange has been created"));

    // FileTransfers initialization
    if (config->isFileTransfersEnabled() &&
        rfbInitializer.getTightEnabledFlag()) {
      fileTransfer = new FileTransferRequestHandler(&codeRegtor, &output, m_desktop, m_log, !m_viewOnly);
      m_log->debug(_T("File transfer has been created"));
    } else {
      m_log->info(_T("File transfer is not allowed"));
    }

    // Second initialization phase
    // Send and receive initialization information between server and viewer
    m_log->debug(_T("View port: (%d,%d) (%dx%d)"), viewPort.left,
                                                 viewPort.top,
                                                 viewPort.getWidth(),
                                                 viewPort.getHeight());
    m_log->info(_T("Entering RFB initialization phase 2"));
    rfbInitializer.afterAuthPhase(&srvToClCaps, &clToSrvCaps,
                                  &encCaps, &Dimension(&viewPort), &pf);
    m_log->debug(_T("RFB initialization phase 2 completed"));

    // Start normal phase
    setClientState(IN_NORMAL_PHASE);

    m_log->info(_T("Entering normal phase of the RFB protocol"));
    dispatcher.resume();

    connClosingEvent.waitForEvent();
  } catch (Exception &e) {
    m_log->error(_T("Connection will be closed: %s"), e.getMessage());
    sysLogMessage.format(_T("The client %s has been")
                         _T(" disconnected for the reason: %s"),
                         peerStr.getString(), e.getMessage());
  }

  disconnect();
  m_newConnectionEvents->onDisconnect(&sysLogMessage);

  // After this call, we are guaranteed not to be used by other threads.
  notifyAbStateChanging(IN_PENDING_TO_REMOVE);

  if (fileTransfer)         delete fileTransfer;
  if (m_clipboardExchange)  delete m_clipboardExchange;
  if (m_clientInputHandler) delete m_clientInputHandler;
  if (m_updateSender)       delete m_updateSender;

  // Let the client manager remove us from the client lists.
  notifyAbStateChanging(IN_READY_TO_REMOVE);
}
Пример #19
0
void RfbClient::notifyAbStateChanging(ClientState state)
{
  setClientState(state);
  m_extTermListener->onClientTerminate();
}