Exemple #1
0
// Original name: CLHNM_LoadFrame
bool HnmPlayer::loadFrame() {
	tryRead(4);
	int chunk = *(int *)_readBuffer;
	chunk = LE32(chunk);
	chunk &= 0xFFFFFF;  // upper bit - keyframe mark?
	if (!chunk)
		return false;

	if (chunk - 4 > _header._bufferSize)
		error("loadFrame - Chunk size");

	tryRead(chunk - 4);
	_dataPtr = _readBuffer;
	return true;
}
Exemple #2
0
// get some data
void Connection::handleRead(const boost::system::error_code& error, size_t len)
{
	if(!error)
	{
		LOGNET() << ">>> got " << len << " data from " 
				<<"id"<<m_id
				<<LOGEND();
		m_offSet += len;
		m_msgBuffer.push_back(std::string(m_buffer, m_buffer+m_offSet));
		m_offSet = 0;
		// continue to read
		tryRead();
		handlePacket();
	}
	else
	{
		if (m_status == CONN_STATUS_CONNECTED)
		{
			m_status = CONN_STATUS_DISCONNECT;
		}
		else
		{
			// triggered by other event
		}
		
		if (m_writeStatus != SW_STATUS_WRITTING)
		{
			m_errHandler(error, this, "handleread");
		}
		else
		{
			// write callback will call immediately
		}
	}
}
bool
RemotePluginClient::hasMIDIInput()
{
    writeOpcode(m_controlRequestFd, RemotePluginHasMIDIInput);
    bool b;
    tryRead(m_controlResponseFd, &b, sizeof(bool));
    return b;
}
void
RemotePluginClient::getParameters(int p0, int pn, float *v)
{
    writeOpcode(m_controlRequestFd, RemotePluginGetParameters);
    writeInt(m_controlRequestFd, p0);
    writeInt(m_controlRequestFd, pn);
    tryRead(m_controlResponseFd, v, (pn - p0 + 1) * sizeof(float));
}
bool
RemotePluginClient::warn(std::string str)
{
    writeOpcode(m_controlRequestFd, RemotePluginWarn);
    writeString(m_controlRequestFd, str);
    bool b;
    tryRead(m_controlResponseFd, &b, sizeof(bool));
    return b;
}
    msg_t main() override
    {
        zubax_chibios::watchdog::Timer wdt;
        wdt.startMSec(1000);
        setName("mag");

        ::usleep(500000);         // Startup delay
        wdt.reset();

        node::markComponentInitialized(node::ComponentID::Magnetometer);

        while (!tryInit() && !node::hasPendingRestartRequest())
        {
            setStatus(uavcan::protocol::NodeStatus::HEALTH_ERROR);
            lowsyslog("Mag init failed, will retry...\n");
            ::usleep(500000);
            wdt.reset();
        }

        wdt.reset();

        const float variance = param_variance.get();
        const uint64_t period_usec = param_period_usec.get();

        systime_t sleep_until = chibios_rt::System::getTime();

        while (!node::hasPendingRestartRequest())
        {
            sleep_until += US2ST(period_usec);

            float vector[3] = {0, 0, 0};
            if (tryRead(vector))
            {
                transformToNEDFrame(vector);
                publish(vector, variance);
                setStatus(estimateStatusFromMeasurement(vector));
            }
            else
            {
                setStatus(uavcan::protocol::NodeStatus::HEALTH_ERROR);
            }

            sysSleepUntilChTime(sleep_until);
            wdt.reset();
        }

        lowsyslog("Mag driver terminated\n");
        return msg_t();
    }
Exemple #7
0
    ssize_t WsConnection::onFrameMaskingKey(const char* data, size_t count)
    {
        ssize_t readLen = tryRead(data, count, 4);
        if(readLen == 0)
        {
            return 0;
        }    

        memcpy(m_maskingKey, m_cache.data(), sizeof(m_maskingKey));
        
        m_cache.clear();
        
        m_status = FrameData;

        return readLen; 
    }
Exemple #8
0
void Connector::handle_read( const boost::system::error_code& error, size_t transferred ) {
    if (error) {
		//	Error receiving data
	    printf( "[Connector (%p)] Warning: Thread received error from socket: msg=%s\n",
			this, error.message().c_str() );
		_io.stop();
    }
	else {
		//printf( "[Connector (%p)] Bytes transferred: %d\n", this, transferred );

		_dataIn.resize(transferred);
		assembleMessage(_dataIn);  // Assemble the received message

		tryRead();
	}
}
void
RemotePluginClient::syncStartup()
{
    // The first (write) fd we open in a nonblocking call, with a
    // short retry loop so we can easily give up if the other end
    // doesn't appear to be responding.  We want a nonblocking FIFO
    // for this anyway.

    bool connected = false;
    int timeout = 40;

    for (int attempt = 0; attempt < timeout; ++attempt) {

	if ((m_controlRequestFd =
	     open(m_controlRequestFileName, O_WRONLY | O_NONBLOCK)) >= 0) {
	    connected = true;
	    break;
	} else if (errno != ENXIO) {
	    // an actual error occurred
	    break;
	}

	sleep(1);
    }

    if (!connected) {
	cleanup();
	throw((std::string)"Plugin server timed out on startup");
    }

    if ((m_controlResponseFd = open(m_controlResponseFileName, O_RDONLY)) < 0) {
	cleanup();
	throw((std::string)"Failed to open control FIFO");
    }

    bool b = false;
    tryRead(m_controlResponseFd, &b, sizeof(bool));
    if (!b) {
	cleanup();
	throw((std::string)"Remote plugin did not start correctly");
    }
}
Exemple #10
0
    ssize_t WsConnection::onFrameData(const char* data, size_t count)
    {
        ssize_t readLen = tryRead(data, count, m_payloadLen);

        if(readLen == 0)
        {
            return 0;    
        }    

        if(isMaskFrame())
        {
            for(size_t i = 0; i < m_cache.size(); ++i)
            {
                m_cache[i] = m_cache[i] ^ m_maskingKey[i % 4];   
            }    
        }

        m_status = FrameFinal;
        return readLen;
    }
Exemple #11
0
    ssize_t WsConnection::onFramePayloadLen16(const char* data, size_t count)
    {
        ssize_t readLen = tryRead(data, count, 2);
        if(readLen == 0)
        {
            return readLen;    
        }
       
        uint16_t payloadLen = *(uint16_t*)m_cache.data();
        //memcpy(&payloadLen, m_cache.data(), sizeof(uint16_t));
        
        if(payloadLen > ms_maxPayloadLen)
        {
            return -1;    
        }

        payloadLen = ntohs(payloadLen); 

        handleFramePayloadLen(payloadLen);

        return readLen; 
    }
Exemple #12
0
    ssize_t WsConnection::onFramePayloadLen64(const char* data, size_t count)
    {
        ssize_t readLen = tryRead(data, count, 8);
        if(readLen == 0)
        {
            return readLen;    
        }

        uint64_t payloadLen = *(uint64_t*)m_cache.data();
        //memcpy(&payloadLen, m_cache.data(), sizeof(uint64_t));
        
        if(payloadLen > ms_maxPayloadLen)
        {
            return -1;
        }

        //todo ntohl64
        payloadLen = be64toh(payloadLen);
        
        handleFramePayloadLen(payloadLen);

        return readLen;
    }
	void handleRequest(ZhttpRequest *_req, const QByteArray &jsonpCallback, const QByteArray &lastPart, const QByteArray &body)
	{
		connect(_req, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int)));
		connect(_req, SIGNAL(error()), SLOT(req_error()));

		if(lastPart == "xhr" || lastPart == "jsonp")
		{
			if(req)
			{
				QVariantList out;
				out += 2010;
				out += QString("Another connection still open");

				requests.insert(_req, new RequestItem(_req, jsonpCallback, RequestItem::Background, true));
				respondOk(_req, out, "c", jsonpCallback);
				return;
			}

			if(peerClosed)
			{
				QVariantList out;
				out += 3000;
				out += QString("Client already closed connection");

				requests.insert(_req, new RequestItem(_req, jsonpCallback, RequestItem::Background, true));
				respondOk(_req, out, "c", jsonpCallback);
				return;
			}

			req = _req;
			requests.insert(req, new RequestItem(req, jsonpCallback, RequestItem::Receive));
			keepAliveTimer->start(KEEPALIVE_TIMEOUT * 1000);

			tryWrite();
		}
		else if(lastPart == "xhr_send" || lastPart == "jsonp_send")
		{
			// only allow one outstanding send request at a time
			if(findFirstSendRequest())
			{
				requests.insert(_req, new RequestItem(_req, jsonpCallback, RequestItem::Background, true));
				respondError(_req, 400, "Bad Request", "Already sending");
				return;
			}

			QByteArray param;

			if(_req->requestMethod() == "POST")
			{
				if(lastPart == "xhr_send")
				{
					// assume json
					param = body;
				}
				else // jsonp_send
				{
					// assume form encoded
					foreach(const QByteArray &kv, body.split('&'))
					{
						int at = kv.indexOf('=');
						if(at == -1)
							continue;
						if(QUrl::fromPercentEncoding(kv.mid(0, at)) == "d")
						{
							param = QUrl::fromPercentEncoding(kv.mid(at + 1)).toUtf8();
							break;
						}
					}
				}
			}
			else // GET
			{
				QUrlQuery query(_req->requestUri());
				param = query.queryItemValue("d").toUtf8();
			}

			QJsonParseError error;
			QJsonDocument doc = QJsonDocument::fromJson(param, &error);
			if(error.error != QJsonParseError::NoError || !doc.isArray())
			{
				requests.insert(_req, new RequestItem(_req, jsonpCallback, RequestItem::Background, true));
				respondError(_req, 400, "Bad Request", "Payload expected");
				return;
			}

			QVariantList messages = doc.array().toVariantList();

			QList<Frame> frames;
			int bytes = 0;
			foreach(const QVariant &vmessage, messages)
			{
				if(vmessage.type() != QVariant::String)
				{
					requests.insert(_req, new RequestItem(_req, jsonpCallback, RequestItem::Background, true));
					respondError(_req, 400, "Bad Request", "Payload expected");
					return;
				}

				QByteArray data = vmessage.toString().toUtf8();
				if(data.size() > BUFFER_SIZE)
				{
					requests.insert(_req, new RequestItem(_req, jsonpCallback, RequestItem::Background, true));
					respondError(_req, 400, "Bad Request", "Message too large");
					return;
				}

				frames += Frame(Frame::Text, data, false);
				bytes += data.size();
			}

			if(frames.isEmpty())
			{
				requests.insert(_req, new RequestItem(_req, jsonpCallback, RequestItem::Background, true));
				respondOk(_req, QString("ok"), jsonpCallback);
				return;
			}

			RequestItem *ri = new RequestItem(_req, jsonpCallback, RequestItem::Send);
			requests.insert(_req, ri);
			ri->sendFrames = frames;
			ri->sendBytes = bytes;

			tryRead();
		}
Exemple #14
0
void Connection::start()
{
	m_connSuccTime = Util::getMSTime();
	m_status = CONN_STATUS_CONNECTED;
	tryRead();
}
Exemple #15
0
void
fuzz(std::string const& filename, el::Level logLevel,
     std::vector<std::string> const& metrics)
{
    Logging::setFmt("<fuzz>", false);
    Logging::setLogLevel(logLevel, nullptr);
    LOG(INFO) << "Fuzzing stellar-core " << STELLAR_CORE_VERSION;
    LOG(INFO) << "Fuzz input is in " << filename;

    Config cfg1, cfg2;

    cfg1.RUN_STANDALONE = true;
    cfg1.ARTIFICIALLY_ACCELERATE_TIME_FOR_TESTING = true;
    cfg1.LOG_FILE_PATH = "fuzz-app-1.log";
    cfg1.TMP_DIR_PATH = "fuzz-tmp-1";
    cfg1.BUCKET_DIR_PATH = "fuzz-buckets-1";

    cfg2.RUN_STANDALONE = true;
    cfg2.ARTIFICIALLY_ACCELERATE_TIME_FOR_TESTING = true;
    cfg1.LOG_FILE_PATH = "fuzz-app-2.log";
    cfg2.TMP_DIR_PATH = "fuzz-tmp-2";
    cfg2.BUCKET_DIR_PATH = "fuzz-buckets-2";

    CfgDirGuard g1(cfg1);
    CfgDirGuard g2(cfg2);

restart:
    {
        VirtualClock clock;
        Application::pointer app1 = Application::create(clock, cfg1);
        Application::pointer app2 = Application::create(clock, cfg2);
        LoopbackPeerConnection loop(*app1, *app2);
        while (clock.crank(false) > 0)
            ;

        XDRInputFileStream in;
        in.open(filename);
        StellarMessage msg;
        size_t i = 0;
        while (tryRead(in, msg))
        {
            ++i;
            if (msg.type() != HELLO)
            {
                LOG(INFO) << "Fuzzer injecting message " << i << ": "
                          << msgSummary(msg);
                loop.getAcceptor()->Peer::sendMessage(msg);
            }
            size_t iter = 20;
            while (clock.crank(false) > 0 && iter-- > 0)
                ;
        }
    }

    if (getenv("AFL_PERSISTENT") && persist_cnt++ < PERSIST_MAX)
    {
#ifndef _WIN32
        raise(SIGSTOP);
#endif
        goto restart;
    }
}
void
RemotePluginServer::dispatchControlEvents()
{    
    RemotePluginOpcode opcode = RemotePluginNoOpcode;
    static float *parameterBuffer = 0;

    tryRead(m_controlRequestFd, &opcode, sizeof(RemotePluginOpcode));

    switch (opcode) {

    case RemotePluginGetVersion:
	writeFloat(m_controlResponseFd, getVersion());
	break;

    case RemotePluginGetName:
	writeString(m_controlResponseFd, getName());
	break;

    case RemotePluginGetMaker:
	writeString(m_controlResponseFd, getMaker());
	break;
    
    case RemotePluginTerminate:
	terminate();
	break;
    
    case RemotePluginGetInputCount:
	m_numInputs = getInputCount();
	writeInt(m_controlResponseFd, m_numInputs);
	break;

    case RemotePluginGetOutputCount:
	m_numOutputs = getOutputCount();
	writeInt(m_controlResponseFd, m_numOutputs);
	break;

    case RemotePluginGetParameterCount:
	writeInt(m_controlResponseFd, getParameterCount());
	break;
	
    case RemotePluginGetParameterName:
	writeString(m_controlResponseFd, getParameterName(readInt(m_controlRequestFd)));
	break;
    
    case RemotePluginGetParameter:
	writeFloat(m_controlResponseFd, getParameter(readInt(m_controlRequestFd)));
	break;
    
    case RemotePluginGetParameterDefault:
	writeFloat(m_controlResponseFd, getParameterDefault(readInt(m_controlRequestFd)));
	break;

    case RemotePluginGetParameters:
    {
	if (!parameterBuffer) {
	    parameterBuffer = new float[getParameterCount()];
	}
	int p0 = readInt(m_controlRequestFd);
	int pn = readInt(m_controlRequestFd);
	getParameters(p0, pn, parameterBuffer);
	tryWrite(m_controlResponseFd, parameterBuffer, (pn - p0 + 1) * sizeof(float));
	break;
    }

    case RemotePluginHasMIDIInput:
    {
	bool m = hasMIDIInput();
	tryWrite(m_controlResponseFd, &m, sizeof(bool));
	break;
    }
       
    case RemotePluginGetProgramCount:
	writeInt(m_controlResponseFd, getProgramCount());
	break;

    case RemotePluginGetProgramName:
	writeString(m_controlResponseFd, getProgramName(readInt(m_controlRequestFd)));
	break;

    case RemotePluginIsReady:
    {
	if (!m_shm) sizeShm();
	bool b(isReady());
	std::cerr << "isReady: returning " << b << std::endl;
	tryWrite(m_controlResponseFd, &b, sizeof(bool));
    }

    case RemotePluginSetDebugLevel:
    {
	RemotePluginDebugLevel newLevel = m_debugLevel;
	tryRead(m_controlRequestFd, &newLevel, sizeof(RemotePluginDebugLevel));
	setDebugLevel(newLevel);
	m_debugLevel = newLevel;
	break;
    }

    case RemotePluginWarn:
    {
	bool b = warn(readString(m_controlRequestFd));
	tryWrite(m_controlResponseFd, &b, sizeof(bool));
	break;
    }

    case RemotePluginShowGUI:
    {
	showGUI(readString(m_controlRequestFd));
	break;
    }

    case RemotePluginHideGUI:
    {
	hideGUI();
	break;
    }

    //Deryabin Andrew: vst chunks support
    case RemotePluginGetVSTChunk:
    {
        std::vector<char> chunk = getVSTChunk();
        writeRaw(m_controlResponseFd, chunk);
        break;
    }

    case RemotePluginSetVSTChunk:
    {
        std::vector<char> chunk = readRaw(m_controlRequestFd);
        setVSTChunk(chunk);
        break;
    }
    //Deryabin Andrew: vst chunks support: end code

    case RemotePluginNoOpcode:
	break;

    case RemotePluginReset:
	reset();
	break;

    default:
	std::cerr << "WARNING: RemotePluginServer::dispatchControlEvents: unexpected opcode "
		  << opcode << std::endl;
    }
}
void
RemotePluginServer::dispatchProcessEvents()
{    
    RemotePluginOpcode opcode = RemotePluginNoOpcode;

    tryRead(&m_shmControl->ringBuffer, &opcode, sizeof(RemotePluginOpcode));

//    std::cerr << "read opcode: " << opcode << std::endl;

    switch (opcode) {

    case RemotePluginProcess:
    {
	if (m_bufferSize < 0) {
	    std::cerr << "ERROR: RemotePluginServer: buffer size must be set before process" << std::endl;
	    return;
	}
	if (m_numInputs < 0) {
	    std::cerr << "ERROR: RemotePluginServer: input count must be tested before process" << std::endl;
	    return;
	}
	if (m_numOutputs < 0) {
	    std::cerr << "ERROR: RemotePluginServer: output count must be tested before process" << std::endl;
	    return;
	}
	if (!m_shm) {
	    sizeShm();
	    if (!m_shm) {
		std::cerr << "ERROR: RemotePluginServer: no shared memory region available" << std::endl;
		return;
	    }
	}

//	std::cerr << "server process: entering" << std::endl;

	size_t blocksz = m_bufferSize * sizeof(float);

	for (int i = 0; i < m_numInputs; ++i) {
	    m_inputs[i] = (float *)(m_shm + i * blocksz);
	}
	for (int i = 0; i < m_numOutputs; ++i) {
	    m_outputs[i] = (float *)(m_shm + (i + m_numInputs) * blocksz);
	}

	process(m_inputs, m_outputs);

//	std::cerr << "server process: written" << std::endl;
	break;
    }
	
    case RemotePluginSetParameter:
    {
        int pn(readInt(&m_shmControl->ringBuffer));
        setParameter(pn, readFloat(&m_shmControl->ringBuffer));
	break;
    }

    case RemotePluginSetCurrentProgram:
	setCurrentProgram(readInt(&m_shmControl->ringBuffer));
	break;

    case RemotePluginSendMIDIData:
    {
	int events = 0;
	int *frameoffsets = 0;
	unsigned char *data = readMIDIData(&m_shmControl->ringBuffer, &frameoffsets, events);
	if (events && data && frameoffsets) {
//    std::cerr << "RemotePluginServer::sendMIDIData(" << events << ")" << std::endl;

	    sendMIDIData(data, frameoffsets, events);
	}
	break;
    }

    case RemotePluginSetBufferSize:
    {
	int newSize = readInt(&m_shmControl->ringBuffer);
	setBufferSize(newSize);
	m_bufferSize = newSize;
	break;
    }

    case RemotePluginSetSampleRate:
	setSampleRate(readInt(&m_shmControl->ringBuffer));
	break;
    
    default:
	std::cerr << "WARNING: RemotePluginServer::dispatchProcessEvents: unexpected opcode "
		  << opcode << std::endl;
    }
}