Exemplo n.º 1
0
/* Write the buffer contents over the network, using a simple
 * packet structure.  The first 4 bytes are a header indicating
 * how many bytes to follow (in the body). */
int writePacket(BIO *conn, char *buffer, int length) {
	//send the header (4 byte int in network byte order)
	uint32_t numBytes = htonl(length);
	int status = writeAll(conn, (char *)&numBytes, sizeof(uint32_t));
	if(status < 1) return status;	

	//send the body (contents of buffer)
	status = writeAll(conn, buffer, length);
	if(status < 1) return status;
	
	return length;
}
Exemplo n.º 2
0
/*
 * Writes an integer array of len length to a file fileName.
 * Returns 0 if successful, 1 if not.
 */
int writeIntArrayFile( const char* fileName, int * ar, size_t len ){
    FILE * matrixFile;
#ifdef OS_LINUX
    matrixFile = fopen( fileName, "w" );
    if( matrixFile==NULL ){
        printf("Error in attempt to write \"%s\" file\n",fileName);
        return 1;
    }
#endif
#ifdef OS_WIN
    errno_t err;
    err = fopen_s( &matrixFile, fileName, "wb" );
    if( err!=0 ){
        printf("Error in attempt to write \"%s\" file\n",fileName);
        return 1;
    }
#endif
    fseek(matrixFile,0,SEEK_SET);       // go to the top of file

    int ret = 0;
    ret = writeFileStart( matrixFile );      if(ret<0) goto writeIntArrayFileLabel;

    size_t sr;
    size_t si;
    si = sizeof(long long int); sr = writeAll( matrixFile, (void *)&len, si );
    if( checkTransfer( "writeCMatrix/1", si, sr, dPRINTOK ) ) goto writeIntArrayFileLabel;

    writeIntArray( matrixFile, ar, len );

    fflush( matrixFile );
writeIntArrayFileLabel:
    fclose(matrixFile);
    return ret;
}
Exemplo n.º 3
0
int main(int argc, char const ** argv)
{
    if (argc < 2)
    {
        std::cerr << "USAGE: basic_seq_io_example FILENAME\n";
        return 1;
    }

    seqan::SequenceStream seqStream(argv[1], seqan::SequenceStream::WRITE);
    if (!isGood(seqStream))
    {
        std::cerr << "ERROR: Could not open the file.\n";
        return 1;
    }

    seqan::StringSet<seqan::CharString> ids;
    appendValue(ids, "seq1");
    appendValue(ids, "seq2");
    seqan::StringSet<seqan::Dna5String> seqs;
    appendValue(seqs, "CGAT");
    appendValue(seqs, "TTTT");

    if (writeAll(seqStream, ids, seqs) != 0)
    {
        std::cerr << "ERROR: Could not write to file!\n";
        return 1;
    }

    return 0;
}
Exemplo n.º 4
0
int writeInt(BIO *conn, int n) {
	uint32_t number = htonl(n);
	int status = writeAll(conn, (char *)&number, sizeof(uint32_t));
	if(status < 1) return status;	

	return 1;
}
Exemplo n.º 5
0
void KProcessPrivate::forwardStd(KProcess::ProcessChannel good, int fd)
{
    Q_Q(KProcess);

    QProcess::ProcessChannel oc = q->readChannel();
    q->setReadChannel(good);
    writeAll(q->readAll(), fd);
    q->setReadChannel(oc);
}
Exemplo n.º 6
0
int writeIntArray( FILE * matrixFile, int * ar, size_t len ){
    size_t sr;  // ret
    size_t si;  // in

    si = len * sizeof(int); sr = writeAll( matrixFile, (void *) ar, si );
    if( checkTransfer( "writeIntArray", si, sr, dPRINTOK ) ) return 1;

    return 0;
}
Exemplo n.º 7
0
int writeInt( FILE * matrixFile, int l ){
    size_t sr;  // ret
    size_t si;  // in

    si = sizeof(int); sr = writeAll( matrixFile, (void *)&l, si );
    if( checkTransfer( "writeInt", si, sr, dPRINTOK ) ) return 1;

    return 0;
}
Exemplo n.º 8
0
void Connection::requestDir() {
    char *buf;
    int msg_size = dir_path.length()+1;

    if (writeAll(this->sock, &msg_size, sizeof(int)) == -1) {
        perror("send dir path length");
        exit(EXIT_FAILURE);
    }
    if ((buf = (char*)malloc((dir_path.length()+1)*sizeof(char))) == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    memcpy(buf, dir_path.c_str(), dir_path.length()+1);
    if (writeAll(this->sock, buf, dir_path.length()+1) == 1) {
        perror("send dir path");
        exit(EXIT_FAILURE);
    }
    free(buf);
}
Exemplo n.º 9
0
bool MaliVideoDriver::start(const int mveUds) {
	char buf[256];
	int pos = 0;

	// code - MVE_INSTR_STARTUP
	buf[pos++] = 'C';
	buf[pos++] = 'L';
	buf[pos++] = 'N';
	buf[pos++] = 'T';
	// size
	Buffer::packInt(buf, sizeof(buf), pos, sizeof(uint32_t));
	// client_version_number
	Buffer::packInt(buf, sizeof(buf), pos, 1);

	// code - MVE_INSTR_CONFIGURE
	buf[pos++] = 'C';
	buf[pos++] = 'N';
	buf[pos++] = 'F';
	buf[pos++] = 'G';
	// size
	Buffer::packInt(buf, sizeof(buf), pos, 5*sizeof(uint32_t));
	// configuration
	Buffer::packInt(buf, sizeof(buf), pos, MVE_INSTR_COUNTERS | MVE_INSTR_EVENTS | MVE_INSTR_ACTIVITIES | MVE_INSTR_PACKED_COMM);
	// communication_protocol_version
	Buffer::packInt(buf, sizeof(buf), pos, 1);
	// data_protocol_version
	Buffer::packInt(buf, sizeof(buf), pos, 1);
	// sample_rate - convert samples/second to ms/sample
	Buffer::packInt(buf, sizeof(buf), pos, gSessionData->mSampleRate/1000);
	// live_rate - convert ns/flush to ms/flush
	Buffer::packInt(buf, sizeof(buf), pos, gSessionData->mLiveRate/1000000);

	// code - MVE_INSTR_ENABLE_COUNTERS
	buf[pos++] = 'C';
	buf[pos++] = 'F';
	buf[pos++] = 'G';
	buf[pos++] = 'c';
	marshalEnable(MVCT_COUNTER, buf, sizeof(buf), pos);

	// code - MVE_INSTR_ENABLE_EVENTS
	buf[pos++] = 'C';
	buf[pos++] = 'F';
	buf[pos++] = 'G';
	buf[pos++] = 'e';
	marshalEnable(MVCT_EVENT, buf, sizeof(buf), pos);

	// code - MVE_INSTR_ENABLE_ACTIVITIES
	buf[pos++] = 'C';
	buf[pos++] = 'F';
	buf[pos++] = 'G';
	buf[pos++] = 'a';
	marshalEnable(MVCT_ACTIVITY, buf, sizeof(buf), pos);

	return writeAll(mveUds, buf, pos);
}
Exemplo n.º 10
0
void testHttpGet() {
    auto sd = std::make_shared<coro::SslSocket>();
    sd->connect(coro::SocketAddr("www.google.com", 443));
    char const buf[] = "GET / HTTP/1.1\nHost: www.google.com\nAccept-Encoding:identity\nConnection: close\n\n";
    sd->writeAll(buf, sizeof(buf)-1); 

    char buf2[4096];
    std::stringstream ss;
    while (ssize_t len = sd->read(buf2, sizeof(buf2))) {
        std::cerr << std::string(buf2, len);
    }
}
Exemplo n.º 11
0
//==============================================================================
String StringArray::joinIntoString (StringRef separator, int start, int numberToJoin) const
{
    auto last = (numberToJoin < 0) ? size()
                                   : jmin (size(), start + numberToJoin);

    if (start < 0)
        start = 0;

    if (start >= last)
        return {};

    if (start == last - 1)
        return strings.getReference (start);

    auto separatorBytes = separator.text.sizeInBytes() - sizeof (String::CharPointerType::CharType);
    auto bytesNeeded = separatorBytes * (size_t) (last - start - 1);

    for (int i = start; i < last; ++i)
        bytesNeeded += strings.getReference(i).getCharPointer().sizeInBytes() - sizeof (String::CharPointerType::CharType);

    String result;
    result.preallocateBytes (bytesNeeded);

    auto dest = result.getCharPointer();

    while (start < last)
    {
        auto& s = strings.getReference (start);

        if (! s.isEmpty())
            dest.writeAll (s.getCharPointer());

        if (++start < last && separatorBytes > 0)
            dest.writeAll (separator.text);
    }

    dest.writeNull();
    return result;
}
Exemplo n.º 12
0
void MaliVideoDriver::stop(const int mveUds) {
	char buf[8];
	int pos = 0;

	// code - MVE_INSTR_STOP
	buf[pos++] = 'S';
	buf[pos++] = 'T';
	buf[pos++] = 'O';
	buf[pos++] = 'P';

	writeAll(mveUds, buf, pos);

	close(mveUds);
}
Exemplo n.º 13
0
void testClientServer() {

    auto c = coro::start([&]{
        auto ls = std::make_shared<coro::SslSocket>();
        ls->bind(coro::SocketAddr("127.0.0.1", 8000));
        ls->listen(10);
		ls->useCertificateFile("test/test.crt");
		ls->usePrivateKeyFile("test/test.key");

        auto sd = ls->accept();

		ls.reset();
        char const buf[] = "foobar\n";
        sd->writeAll(buf, sizeof(buf)-1);

		char buf2[4096];
		while (sd->read(buf2, sizeof(buf2))) {
		}
    });

    auto s = coro::start([&]{
        auto sd = std::make_shared<coro::SslSocket>();
        sd->connect(coro::SocketAddr("127.0.0.1", 8000));

        char const buf[] = "GET / HTTP/1.1\nHost: 127.0.0.1\nConnection: close\n\n";
        sd->writeAll(buf, sizeof(buf)-1); 
		sd->shutdown(SHUT_WR);
    
        char buf2[4096];
        std::stringstream ss;
        while (ssize_t len = sd->read(buf2, sizeof(buf2))) {
            std::cerr << std::string(buf2, len);
        }
    });

    s->join();
}
Exemplo n.º 14
0
/* Send a file across the network. The filename argument
 * will be sent to indicate to the other side what it should
 * be saved as. */
int writeFile(BIO *conn, char *filename, char *writeName) {
	//if no alternate name supplied, just use it's actual name
	if(writeName == NULL) writeName = filename;

	FILE *ifp = fopen(filename, "rb");
	if(ifp == NULL) {
		perror("writeFile");
		//send NO_SUCH_FILE as the file length to indicate file is not coming
		writeInt(conn, NO_SUCH_FILE);
		return NO_SUCH_FILE;
	}

	//send the file length in 4 bytes
	int fileSize = sizeOfFile(filename);
	if(writeInt(conn, fileSize) == -1) return -1;
	if(fileSize == -1) return -1;
	
	//send the filename first in a simple packet
	if(writeString(conn, writeName) < 1) return -1;

	/* Now transfer the file */
	char fileBuffer[BUFSIZ];
	while(fileSize > 0) {
		//read a chunk
		int numRead = fread(fileBuffer, 1, BUFSIZ, ifp); 
		if(numRead == 0) break;

		//send that chunk over the network
		int status = writeAll(conn, fileBuffer, numRead);
		if(status < 1) return status;

		fileSize -= numRead;
	}

	if(fileSize != 0) {
		fprintf(stderr, "writeFile(): fileSize non-zero after sending. Incomplete??\n");
		return -1;
	}

	return 1;
}
behaviour_settings::behaviour_settings(QWidget *parent) :
    QWidget(parent)
{

  QLabel *lbl = new QLabel(tr("<b>Under the Hood</b>"));
  trCon = new QCheckBox(tr("Tray Icon           *May Require Restart"));
  notifi = new QCheckBox(tr("Allow Notifications"));
  runBhd = new QCheckBox(tr("Keep Running in the Background"));
  quitPlistEnd = new QCheckBox(tr("Quit at the end of playlist"));
  QPushButton * apli = new QPushButton(tr("Apply"));

 QBoxLayout *hlay = new QHBoxLayout;
 hlay->addStretch(1);
 hlay->addWidget(apli);


 QBoxLayout *vlay = new QVBoxLayout;
 vlay->setMargin(0);
 vlay->setSpacing(0);
 vlay->addWidget(lbl);
 vlay->addWidget(trCon);
 vlay->addWidget(runBhd);
 vlay->addWidget(notifi);
 vlay->addWidget(quitPlistEnd);
 vlay->addLayout(hlay);
 vlay->insertStretch(12);

 setLayout(vlay);
 flags = new QMap<QString, QVariant>;

 connect(notifi,SIGNAL(stateChanged(int)),this,SLOT(ntfyType(int)));
 connect(trCon, SIGNAL(stateChanged(int)),this,SLOT(tray(int)));
 connect(runBhd, SIGNAL(stateChanged(int)),this,SLOT(bckgd(int)));
 connect(quitPlistEnd,SIGNAL(stateChanged(int)),this,SLOT(quitPlaylistEnd(int)));
 connect(apli,SIGNAL(clicked()),this,SLOT(writeAll()));

 readSettings();


}
bool MCCacheWriter::writeCacheFile(FileHandle *objFile, FileHandle *infoFile,
                                 Script *S, uint32_t libRS_threadable) {
  if (!objFile || objFile->getFD() < 0 || !infoFile || infoFile->getFD() < 0) {
    return false;
  }

  mObjFile = objFile;
  mInfoFile = infoFile;
  mpOwner = S;

  bool result = prepareHeader(libRS_threadable)
             && prepareDependencyTable()
             && preparePragmaList()
             && prepareExportVarNameList()
             && prepareExportFuncNameList()
             && prepareExportForEachNameList()
             && prepareStringPool()
             && prepareObjectSlotList()
             && calcSectionOffset()
             && writeAll()
             ;

  return result;
}
Exemplo n.º 17
0
void MainWidget::closeEvent(QCloseEvent*) {
	writeAll(treeFileName(), ui.tree->serialize());
}
Exemplo n.º 18
0
void eStreamClient::notifier(int what)
{
	if (!(what & eSocketNotifier::Read))
		return;

	ePtr<eStreamClient> ref = this;
	char buf[512];
	int len;
	if ((len = singleRead(streamFd, buf, sizeof(buf))) <= 0)
	{
		rsn->stop();
		stop();
		parent->connectionLost(this);
		return;
	}
	request.append(buf, len);
	if (running || (request.find('\n') == std::string::npos))
		return;

	if (request.substr(0, 5) == "GET /")
	{
		size_t pos;
		size_t posdur;
		if (eConfigManager::getConfigBoolValue("config.streaming.authentication"))
		{
			bool authenticated = false;
			if ((pos = request.find("Authorization: Basic ")) != std::string::npos)
			{
				std::string authentication, username, password;
				std::string hash = request.substr(pos + 21);
				pos = hash.find('\r');
				hash = hash.substr(0, pos);
				authentication = base64decode(hash);
				pos = authentication.find(':');
				if (pos != std::string::npos)
				{
					char *buffer = (char*)malloc(4096);
					if (buffer)
					{
						struct passwd pwd;
						struct passwd *pwdresult = NULL;
						std::string crypt;
						username = authentication.substr(0, pos);
						password = authentication.substr(pos + 1);
						getpwnam_r(username.c_str(), &pwd, buffer, 4096, &pwdresult);
						if (pwdresult)
						{
							struct crypt_data cryptdata;
							char *cryptresult = NULL;
							cryptdata.initialized = 0;
							crypt = pwd.pw_passwd;
							if (crypt == "*" || crypt == "x")
							{
								struct spwd spwd;
								struct spwd *spwdresult = NULL;
								getspnam_r(username.c_str(), &spwd, buffer, 4096, &spwdresult);
								if (spwdresult)
								{
									crypt = spwd.sp_pwdp;
								}
							}
							cryptresult = crypt_r(password.c_str(), crypt.c_str(), &cryptdata);
							authenticated = cryptresult && cryptresult == crypt;
						}
						free(buffer);
					}
				}
			}
			if (!authenticated)
			{
				const char *reply = "HTTP/1.0 401 Authorization Required\r\nWWW-Authenticate: Basic realm=\"streamserver\"\r\n\r\n";
				writeAll(streamFd, reply, strlen(reply));
				rsn->stop();
				parent->connectionLost(this);
				return;
			}
		}
		pos = request.find(' ', 5);
		if (pos != std::string::npos)
		{
			std::string serviceref = urlDecode(request.substr(5, pos - 5));
			if (!serviceref.empty())
			{
				const char *reply = "HTTP/1.0 200 OK\r\nConnection: Close\r\nContent-Type: video/mpeg\r\nServer: streamserver\r\n\r\n";
				writeAll(streamFd, reply, strlen(reply));
				/* We don't expect any incoming data, so set a tiny buffer */
				set_socket_option(streamFd, SO_RCVBUF, 1 * 1024);
				 /* We like 188k packets, so set the TCP window size to that */
				set_socket_option(streamFd, SO_SNDBUF, 188 * 1024);
				/* activate keepalive */
				set_socket_option(streamFd, SO_KEEPALIVE, 1);
				/* configure keepalive */
				set_tcp_option(streamFd, TCP_KEEPINTVL, 10); // every 10 seconds
				set_tcp_option(streamFd, TCP_KEEPIDLE, 1);	// after 1 second of idle
				set_tcp_option(streamFd, TCP_KEEPCNT, 2);	// drop connection after second miss
				/* also set 10 seconds data push timeout */
				set_tcp_option(streamFd, TCP_USER_TIMEOUT, 10 * 1000);

				if (serviceref.substr(0, 10) == "file?file=") /* convert openwebif stream reqeust back to serviceref */
					serviceref = "1:0:1:0:0:0:0:0:0:0:" + serviceref.substr(10);
				/* Strip session ID from URL if it exists, PLi streaming can not handle it */
				pos = serviceref.find("&sessionid=");
				if (pos != std::string::npos) {
					serviceref.erase(pos, std::string::npos);
				}
				pos = serviceref.find("?sessionid=");
				if (pos != std::string::npos) {
					serviceref.erase(pos, std::string::npos);
				}
				pos = serviceref.find('?');
				if (pos == std::string::npos)
				{
					eDebug("[eDVBServiceStream] stream ref: %s", serviceref.c_str());
					if (eDVBServiceStream::start(serviceref.c_str(), streamFd) >= 0)
					{
						running = true;
						m_serviceref = serviceref;
						m_useencoder = false;
					}
				}
				else
				{
					request = serviceref.substr(pos);
					serviceref = serviceref.substr(0, pos);
					pos = request.find("?bitrate=");
					posdur = request.find("?duration=");
					eDebug("[eDVBServiceStream] stream ref: %s", serviceref.c_str());
					if (posdur != std::string::npos)
					{
						if (eDVBServiceStream::start(serviceref.c_str(), streamFd) >= 0)
						{
							running = true;
							m_serviceref = serviceref;
							m_useencoder = false;
						}
						int timeout = 0;
						sscanf(request.substr(posdur).c_str(), "?duration=%d", &timeout);
						eDebug("[eDVBServiceStream] duration: %d seconds", timeout);
						if (timeout)
						{
							m_timeout->startLongTimer(timeout);
						}
					}
					else if (pos != std::string::npos)
					{
						/* we need to stream transcoded data */
						int bitrate = 1024 * 1024;
						int width = 720;
						int height = 576;
						int framerate = 25000;
						int interlaced = 0;
						int aspectratio = 0;
						sscanf(request.substr(pos).c_str(), "?bitrate=%d", &bitrate);
						pos = request.find("?width=");
						if (pos != std::string::npos)
							sscanf(request.substr(pos).c_str(), "?width=%d", &width);
						pos = request.find("?height=");
						if (pos != std::string::npos)
							sscanf(request.substr(pos).c_str(), "?height=%d", &height);
						pos = request.find("?framerate=");
						if (pos != std::string::npos)
							sscanf(request.substr(pos).c_str(), "?framerate=%d", &framerate);
						pos = request.find("?interlaced=");
						if (pos != std::string::npos)
							sscanf(request.substr(pos).c_str(), "?interlaced=%d", &interlaced);
						pos = request.find("?aspectratio=");
						if (pos != std::string::npos)
							sscanf(request.substr(pos).c_str(), "?aspectratio=%d", &aspectratio);
						encoderFd = -1;
						if (eEncoder::getInstance())
							encoderFd = eEncoder::getInstance()->allocateEncoder(serviceref, bitrate, width, height, framerate, !!interlaced, aspectratio);
						if (encoderFd >= 0)
						{
							running = true;
							streamThread = new eDVBRecordStreamThread(188);
							if (streamThread)
							{
								streamThread->setTargetFD(streamFd);
								streamThread->start(encoderFd);
							}
							m_serviceref = serviceref;
							m_useencoder = true;
						}
					}
				}
			}
		}
	}
	if (!running)
	{
		const char *reply = "HTTP/1.0 400 Bad Request\r\n\r\n";
		writeAll(streamFd, reply, strlen(reply));
		rsn->stop();
		parent->connectionLost(this);
		return;
	}
	request.clear();
}
Exemplo n.º 19
0
int eHttpStream::openUrl(const std::string &url, std::string &newurl)
{
	int port;
	std::string hostname;
	std::string uri = url;
	std::string request;
	size_t buflen = 1024;
	char *linebuf = NULL;
	int result;
	char proto[100];
	int statuscode = 0;
	char statusmsg[100];
	bool playlist = false;
	bool contenttypeparsed = false;

	close();

	int pathindex = uri.find("/", 7);
	if (pathindex > 0)
	{
		hostname = uri.substr(7, pathindex - 7);
		uri = uri.substr(pathindex, uri.length() - pathindex);
	}
	else
	{
		hostname = uri.substr(7, uri.length() - 7);
		uri = "/";
	}
	int authenticationindex = hostname.find("@");
	if (authenticationindex > 0)
	{
		BIO *mbio, *b64bio, *bio;
		char *p = (char*)NULL;
		int length = 0;
		authorizationData = hostname.substr(0, authenticationindex);
		hostname = hostname.substr(authenticationindex + 1);
		mbio = BIO_new(BIO_s_mem());
		b64bio = BIO_new(BIO_f_base64());
		bio = BIO_push(b64bio, mbio);
		BIO_write(bio, authorizationData.c_str(), authorizationData.length());
		BIO_flush(bio);
		length = BIO_ctrl(mbio, BIO_CTRL_INFO, 0, (char*)&p);
		authorizationData = "";
		if (p && length > 0)
		{
			/* base64 output contains a linefeed, which we ignore */
			authorizationData.append(p, length - 1);
		}
		BIO_free_all(bio);
	}
	int customportindex = hostname.find(":");
	if (customportindex > 0)
	{
		port = atoi(hostname.substr(customportindex + 1, hostname.length() - customportindex - 1).c_str());
		hostname = hostname.substr(0, customportindex);
	}
	else if (customportindex == 0)
	{
		port = atoi(hostname.substr(1, hostname.length() - 1).c_str());
		hostname = "localhost";
	}
	else
	{
		port = 80;
	}
	streamSocket = Connect(hostname.c_str(), port, 10);
	if (streamSocket < 0)
		goto error;

	request = "GET ";
	request.append(uri).append(" HTTP/1.1\r\n");
	request.append("Host: ").append(hostname).append("\r\n");
	request.append("User-Agent: ").append("Enigma2").append("\r\n");
	if (authorizationData != "")
	{
		request.append("Authorization: Basic ").append(authorizationData).append("\r\n");
	}
	request.append("Accept: */*\r\n");
	request.append("Connection: close\r\n");
	request.append("\r\n");

	writeAll(streamSocket, request.c_str(), request.length());

	linebuf = (char*)malloc(buflen);

	result = readLine(streamSocket, &linebuf, &buflen);
	if (result <= 0)
		goto error;

	result = sscanf(linebuf, "%99s %d %99s", proto, &statuscode, statusmsg);
	if (result != 3 || (statuscode != 200 && statuscode != 206 && statuscode != 302))
	{
		eDebug("%s: wrong http response code: %d", __FUNCTION__, statuscode);
		goto error;
	}

	while (1)
	{
		result = readLine(streamSocket, &linebuf, &buflen);
		if (!contenttypeparsed)
		{
			char contenttype[33];
			if (sscanf(linebuf, "Content-Type: %32s", contenttype) == 1)
			{
				contenttypeparsed = true;
				if (!strcasecmp(contenttype, "application/text")
				|| !strcasecmp(contenttype, "audio/x-mpegurl")
				|| !strcasecmp(contenttype, "audio/mpegurl")
				|| !strcasecmp(contenttype, "application/m3u"))
				{
					/* assume we'll get a playlist, some text file containing a stream url */
					playlist = true;
				}
				continue;
			}
		}
		if (playlist && !strncasecmp(linebuf, "http://", 7))
		{
			newurl = linebuf;
			eDebug("%s: playlist entry: %s", __FUNCTION__, newurl.c_str());
			break;
		}
		if (((statuscode == 301) || (statuscode == 302) || (statuscode == 303) || (statuscode == 307) || (statuscode == 308)) &&
				strncasecmp(linebuf, "location: ", 10) == 0)
		{
			newurl = &linebuf[10];
			eDebug("%s: redirecting to: %s", __FUNCTION__, newurl.c_str());
			break;
		}

		if (((statuscode == 200) || (statuscode == 206)) && !strncasecmp(linebuf, "transfer-encoding: chunked", strlen("transfer-encoding: chunked")))
		{
			isChunked = true;
		}
		if (!playlist && result == 0)
			break;
		if (result < 0)
			break;
	}

	free(linebuf);
	return 0;
error:
	eDebug("%s failed", __FUNCTION__);
	free(linebuf);
	close();
	return -1;
}
Exemplo n.º 20
0
void make_bed(int argc,char **argv){
  //  fprintf(stderr,"[%s] \n",__FUNCTION__);
  if(argc==0){
    fprintf(stderr,"make_bed FILE.theta.gz [OUTNAMES] (if OUTNAMES is supplied, this will be used as prefix \n");
    exit(0);
  }
  
  if(!fexists(argv[0])){
    fprintf(stderr,"Problem opening file: %s\n",argv[0]);
    exit(0);
  }
  char *base = argv[0];
  if(argc==2)
    base = argv[1];

  char* outnames_bin = append(base,BIN);
  char* outnames_idx = append(base,IDX);
    
  const char *delims = "\t \n";
  gzFile gfp = gzopen(argv[0],"r");
  char *buf = new char[LENS];
  BGZF *cfpD = bgzf_open(outnames_bin,"w9");
  FILE *fp =fopen(outnames_idx,"w");
  
  std::vector<the_t> vec;
  char *lastChr = NULL;
  
  
  while(gzgets(gfp,buf,LENS)){
    char *chr = strtok(buf,delims);
    if(chr[0]=='#')
      continue;
    int posi=atoi(strtok(NULL,delims)) ;
    
    if(lastChr==NULL){
      lastChr = strdup(chr);
    }else if(strcmp(lastChr,chr)!=0){
      int64_t id=writeAll(vec,lastChr,cfpD);//write data
      write_index(vec.size(),lastChr,fp,id);//write index;
      
      vec.clear();
      free(lastChr);
      lastChr=strdup(chr);
    }
    the_t t;
    t.posi =posi;
    float *the =new float[5];
    for(int i=0;i<5;i++)
      the[i] = atof(strtok(NULL,delims)) ;
    t.vals = the;
    vec.push_back(t);
#if 0
    fprintf(stderr,"%s %d ",chr,posi);
    for(int i=0;i<5;i++)
      fprintf(stderr," %f",the[i]);
    fprintf(stderr,"\n");
#endif
  }
  int64_t id=writeAll(vec,lastChr,cfpD);//write data
  write_index(vec.size(),lastChr,fp,id);//write index;
  vec.clear();
  free(lastChr);
  
  fprintf(stderr,"\tHas dumped files:\n\t\t'%s\'\n\t\t\'%s\'\n",outnames_bin,outnames_idx);
  bgzf_close(cfpD);
  fclose(fp);
  
  gzclose(gfp);
  delete [] buf;
  delete [] outnames_bin; delete [] outnames_idx;
}
Exemplo n.º 21
0
void eStreamClient::notifier(int what)
{
	if (!(what & eSocketNotifier::Read))
		return;

	ePtr<eStreamClient> ref = this;
	char buf[512];
	int len;
	if ((len = singleRead(streamFd, buf, sizeof(buf))) <= 0)
	{
		rsn->stop();
		stop();
		parent->connectionLost(this);
		return;
	}
	request.append(buf, len);
	if (running || (request.find('\n') == std::string::npos))
		return;

	if (request.substr(0, 5) == "GET /")
	{
		size_t pos;
		if (eConfigManager::getConfigBoolValue("config.streaming.authentication"))
		{
			bool authenticated = false;
			if ((pos = request.find("Authorization: Basic ")) != std::string::npos)
			{
				std::string authentication, username, password;
				std::string hash = request.substr(pos + 21);
				pos = hash.find('\r');
				hash = hash.substr(0, pos);
				hash += "\n";
				{
					char *in, *out;
					in = strdup(hash.c_str());
					out = (char*)calloc(1, hash.size());
					if (in && out)
					{
						BIO *b64, *bmem;
						b64 = BIO_new(BIO_f_base64());
						bmem = BIO_new_mem_buf(in, hash.size());
						bmem = BIO_push(b64, bmem);
						BIO_read(bmem, out, hash.size());
						BIO_free_all(bmem);
						authentication.append(out, hash.size());
					}
					free(in);
					free(out);
				}
				pos = authentication.find(':');
				if (pos != std::string::npos)
				{
					char *buffer = (char*)malloc(4096);
					if (buffer)
					{
						struct passwd pwd;
						struct passwd *pwdresult = NULL;
						std::string crypt;
						username = authentication.substr(0, pos);
						password = authentication.substr(pos + 1);
						getpwnam_r(username.c_str(), &pwd, buffer, 4096, &pwdresult);
						if (pwdresult)
						{
							struct crypt_data cryptdata;
							char *cryptresult = NULL;
							cryptdata.initialized = 0;
							crypt = pwd.pw_passwd;
							if (crypt == "*" || crypt == "x")
							{
								struct spwd spwd;
								struct spwd *spwdresult = NULL;
								getspnam_r(username.c_str(), &spwd, buffer, 4096, &spwdresult);
								if (spwdresult)
								{
									crypt = spwd.sp_pwdp;
								}
							}
							cryptresult = crypt_r(password.c_str(), crypt.c_str(), &cryptdata);
							authenticated = cryptresult && cryptresult == crypt;
						}
						free(buffer);
					}
				}
			}
			if (!authenticated)
			{
				const char *reply = "HTTP/1.0 401 Authorization Required\r\nWWW-Authenticate: Basic realm=\"streamserver\"\r\n\r\n";
				writeAll(streamFd, reply, strlen(reply));
				rsn->stop();
				parent->connectionLost(this);
				return;
			}
		}
		pos = request.find(' ', 5);
		if (pos != std::string::npos)
		{
			std::string serviceref = urlDecode(request.substr(5, pos - 5));
			if (!serviceref.empty())
			{
				const char *reply = "HTTP/1.0 200 OK\r\nConnection: Close\r\nContent-Type: video/mpeg\r\nServer: streamserver\r\n\r\n";
				writeAll(streamFd, reply, strlen(reply));
				if (serviceref.substr(0, 10) == "file?file=") /* convert openwebif stream reqeust back to serviceref */
					serviceref = "1:0:1:0:0:0:0:0:0:0:" + serviceref.substr(10);
				pos = serviceref.find('?');
				if (pos == std::string::npos)
				{
					if (eDVBServiceStream::start(serviceref.c_str(), streamFd) >= 0)
						running = true;
				}
				else
				{
					request = serviceref.substr(pos);
					serviceref = serviceref.substr(0, pos);
					pos = request.find("?bitrate=");
					if (pos != std::string::npos)
					{
						/* we need to stream transcoded data */
						int bitrate = 1024 * 1024;
						int width = 720;
						int height = 576;
						int framerate = 25000;
						int interlaced = 0;
						int aspectratio = 0;
						sscanf(request.substr(pos).c_str(), "?bitrate=%d", &bitrate);
						pos = request.find("?width=");
						if (pos != std::string::npos)
							sscanf(request.substr(pos).c_str(), "?width=%d", &width);
						pos = request.find("?height=");
						if (pos != std::string::npos)
							sscanf(request.substr(pos).c_str(), "?height=%d", &height);
						pos = request.find("?framerate=");
						if (pos != std::string::npos)
							sscanf(request.substr(pos).c_str(), "?framerate=%d", &framerate);
						pos = request.find("?interlaced=");
						if (pos != std::string::npos)
							sscanf(request.substr(pos).c_str(), "?interlaced=%d", &interlaced);
						pos = request.find("?aspectratio=");
						if (pos != std::string::npos)
							sscanf(request.substr(pos).c_str(), "?aspectratio=%d", &aspectratio);
						encoderFd = parent->allocateEncoder(this, serviceref, bitrate, width, height, framerate, !!interlaced, aspectratio);
						if (encoderFd >= 0)
						{
							running = true;
							streamThread = new eDVBRecordStreamThread(188);
							if (streamThread)
							{
								streamThread->setTargetFD(streamFd);
								streamThread->start(encoderFd);
							}
						}
					}
				}
			}
		}
	}
	if (!running)
	{
		const char *reply = "HTTP/1.0 400 Bad Request\r\n\r\n";
		writeAll(streamFd, reply, strlen(reply));
		rsn->stop();
		parent->connectionLost(this);
		return;
	}
	request.clear();
}
/// <summary>
/// Enables the camera preview.
/// </summary>
/// <param name="enable">true to enable, false to disable.</param>
/// <returns>int.</returns>
int Camera::enablePreview(bool enable)
{
	EPtr eptrs[] = { EPtr(ACTION, enable ? ENABLE : DISABLE), EPtr(MESSAGE, PREVIEW) };
	return writeAll(SERVICE_CAMERA, eptrs, 2);
}
/// <summary>
/// Captures a picture and optionally saves/sends it to the specified URL.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns>int.</returns>
int Camera::capture(String url)
{
	EPtr eptrs[] = { EPtr(url ? MemPtr : None, URL, url.c_str()) };
	return shield.block(writeAll(SERVICE_CAMERA, eptrs, 1), onEvent == 0);
}
Exemplo n.º 24
0
int eHttpStream::openHttpConnection()
{
	int port;
	std::string hostname;
	std::string uri = url;
	std::string request;
	size_t buflen = 1024;
	char *linebuf = NULL;
	int result;
	char proto[100];
	int statuscode = 0;
	char statusmsg[100];
	bool redirected = false;

	close();

	int pathindex = uri.find("/", 7);
	if (pathindex > 0) 
	{
		hostname = uri.substr(7, pathindex - 7);
		uri = uri.substr(pathindex, uri.length() - pathindex);
	} 
	else 
	{
		hostname = uri.substr(7, uri.length() - 7);
		uri = "";
	}
	int customportindex = hostname.find(":");
	if (customportindex > 0) 
	{
		port = atoi(hostname.substr(customportindex + 1, hostname.length() - customportindex - 1).c_str());
		hostname = hostname.substr(0, customportindex);
	} 
	else if (customportindex == 0) 
	{
		port = atoi(hostname.substr(1, hostname.length() - 1).c_str());
		hostname = "localhost";
	}
	else
	{
		port = 80;
	}
	streamSocket = connect(hostname.c_str(), port, 10);
	if (streamSocket < 0) goto error;

	request = "GET ";
	request.append(uri).append(" HTTP/1.1\r\n");
	request.append("Host: ").append(hostname).append("\r\n");
	request.append("Accept: */*\r\n");
	request.append("Connection: close\r\n");
	request.append("\r\n");
	writeAll(streamSocket, request.c_str(), request.length());

	linebuf = (char*)malloc(buflen);

	result = readLine(streamSocket, &linebuf, &buflen);
	if (result <= 0) goto error;

	result = sscanf(linebuf, "%99s %d %99s", proto, &statuscode, statusmsg);
	if (result != 3 || (statuscode != 200 && statuscode != 302))
	{
		eDebug("eHttpStream::open: wrong http response code: %d", statuscode);
		goto error;
	}

	while (result > 0)
	{
		result = readLine(streamSocket, &linebuf, &buflen);
		if (statuscode == 302 && sscanf(linebuf, "Location: %999s", this->url) == 1)
		{
				eDebug("eHttpStream::open: redirecting");
				if (openHttpConnection() < 0) goto error;
				redirected = true;
				break;
		}
	}
	if (statuscode == 302 && !redirected) goto error;

	free(linebuf);
	return 0;
error:
	eDebug("eHttpStream::open failed");
	free(linebuf);
	close();
	return -1;
}
Exemplo n.º 25
0
void eStreamClient::notifier(int what)
{
	if (what & eSocketNotifier::Read)
	{
		char buf[512];
		int len;
		if ((len = singleRead(streamFd, buf, sizeof(buf))) <= 0)
		{
			rsn->stop();
			stop();
			parent->connectionLost(this);
			return;
		}
		request.append(buf, len);
		if (!running)
		{
			if (request.find('\n') != std::string::npos)
			{
				if (request.substr(0, 5) == "GET /")
				{
					size_t pos;
					if (eConfigManager::getConfigBoolValue("config.streaming.authentication"))
					{
						bool authenticated = false;
						if ((pos = request.find("Authorization: Basic ")) != std::string::npos)
						{
							std::string authentication, username, password;
							std::string hash = request.substr(pos + 21);
							pos = hash.find('\r');
							hash = hash.substr(0, pos);
							hash += "\n";
							{
								char *in, *out;
								in = strdup(hash.c_str());
								out = (char*)calloc(1, hash.size());
								if (in && out)
								{
									BIO *b64, *bmem;
									b64 = BIO_new(BIO_f_base64());
									bmem = BIO_new_mem_buf(in, hash.size());
									bmem = BIO_push(b64, bmem);
									BIO_read(bmem, out, hash.size());
									BIO_free_all(bmem);
									authentication.append(out, hash.size());
								}
								free(in);
								free(out);
							}
							pos = authentication.find(':');
							if (pos != std::string::npos)
							{
								char *buffer = (char*)malloc(4096);
								if (buffer)
								{
									struct passwd pwd;
									struct passwd *pwdresult = NULL;
									std::string crypt;
									username = authentication.substr(0, pos);
									password = authentication.substr(pos + 1);
									getpwnam_r(username.c_str(), &pwd, buffer, 4096, &pwdresult);
									if (pwdresult)
									{
										struct crypt_data cryptdata;
										char *cryptresult = NULL;
										cryptdata.initialized = 0;
										crypt = pwd.pw_passwd;
										if (crypt == "*" || crypt == "x")
										{
											struct spwd spwd;
											struct spwd *spwdresult = NULL;
											getspnam_r(username.c_str(), &spwd, buffer, 4096, &spwdresult);
											if (spwdresult)
											{
												crypt = spwd.sp_pwdp;
											}
										}
										cryptresult = crypt_r(password.c_str(), crypt.c_str(), &cryptdata);
										authenticated = cryptresult && cryptresult == crypt;
									}
									free(buffer);
								}
							}
						}
						if (!authenticated)
						{
							const char *reply = "HTTP/1.0 401 Authorization Required\r\nWWW-Authenticate: Basic realm=\"streamserver\"\r\n\r\n";
							writeAll(streamFd, reply, strlen(reply));
							rsn->stop();
							parent->connectionLost(this);
							return;
						}
					}
					pos = request.find(' ', 5);
					if (pos != std::string::npos)
					{
						std::string serviceref = urlDecode(request.substr(5, pos - 5));
						if (!serviceref.empty())
						{
							const char *reply = "HTTP/1.0 200 OK\r\nConnection: Close\r\nContent-Type: video/mpeg\r\nServer: streamserver\r\n\r\n";
							writeAll(streamFd, reply, strlen(reply));
							if (eDVBServiceStream::start(serviceref.c_str(), streamFd) >= 0)
							{
								running = true;
							}
						}
					}
				}
				if (!running)
				{
					const char *reply = "HTTP/1.0 400 Bad Request\r\n\r\n";
					writeAll(streamFd, reply, strlen(reply));
					rsn->stop();
					parent->connectionLost(this);
					return;
				}
				request.clear();
			}
		}
	}
}
Exemplo n.º 26
0
int main(int argc, char *argv[])
{
    const char *colon;
    int port;
    struct stat st;
    char buffer[BUFSIZ];
    int len;

    // Validate the command-line parameters.
    if ( argc > 1 ) {
        // Use the supplied device name.
        device = argv[1];
    } else {
        // Look for QTOPIA_PHONE_DEVICE and use that if set.
        device = getenv( "QTOPIA_PHONE_DEVICE" );
    }
    if ( argc > 2 ) {
        // Use the supplied port number.
        port = atoi( argv[2] );
    } else {
        // Use the default phonesim port.
        port = 12345;
    }
    if ( !device || port <= 0 ) {
        fprintf( stderr, "Usage: %s device[:baudrate] [port]\n", argv[0] );
        return 1;
    }

    // Split the device specification into name and baud rate.
    colon = strchr( device, ':' );
    if ( colon ) {
        baudRate = atoi( colon + 1 );
        char *dev = strdup( device );
        dev[colon - device] = '\0';
        device = dev;
    } else {
        baudRate = 115200;
    }

    // Check to see if the device seems to exist.  We only open
    // it when the connection arrives from the host.
    if ( stat( device, &st ) < 0 ) {
        perror( "stat" );
        return 1;
    }

    // Bind to the server port to wait for incoming connections.
    listenFd = openServer( port );
    if ( listenFd < 0 ) {
        return 1;
    }

    // Enter the select loop and process events as they arrive.
    for (;;) {
        fd_set readSet;
        int maxFd = listenFd;
        FD_ZERO(&readSet);
        FD_SET(listenFd, &readSet);
        if ( connectionFd != -1 ) {
            FD_SET(connectionFd, &readSet);
            if ( connectionFd > maxFd )
                maxFd = connectionFd;
        }
        if ( deviceFd != -1 ) {
            FD_SET(deviceFd, &readSet);
            if ( deviceFd > maxFd )
                maxFd = deviceFd;
        }
        int result = ::select( maxFd + 1, &readSet, (fd_set *)0,
                               (fd_set *)0, (struct timeval *)0 );
        if ( result < 0 ) {
            // Signal interrupts are ok, but everything else should report.
            if ( errno != EINTR )
                perror( "select" );
        } else {
            if ( FD_ISSET(listenFd, &readSet) ) {
                // Accept a new incoming connection.
                if ( connectionFd != -1 ) {
                    // There is an existing connection - kill it because
                    // the host on the other end has probably crashed.
                    ::close( connectionFd );
                }
                connectionFd = ::accept( listenFd, (struct sockaddr *)0, 0 );
                if ( connectionFd < 0 )
                    perror( "accept" );
                deviceFd = openDevice();
                if ( deviceFd < 0 ) {
                    // Abort the connection if device cannot be opened.
                    ::close( connectionFd );
                    connectionFd = -1;
                }
            }
            if ( connectionFd != -1 && FD_ISSET(connectionFd, &readSet) ) {
                // Read data from the connection and write to the device.
                len = ::read( connectionFd, buffer, sizeof(buffer) );
                if ( len == 0 ) {
                    // The connection has closed.
                    ::close( connectionFd );
                    ::close( deviceFd );
                    connectionFd = -1;
                    deviceFd = -1;
                } else if ( len > 0 ) {
                    writeAll( deviceFd, buffer, len );
                }
            }
            if ( deviceFd != -1 && FD_ISSET(deviceFd, &readSet) ) {
                // Read data from the device and write to the connection.
                len = ::read( deviceFd, buffer, sizeof(buffer) );
                if ( len == 0 ) {
                    // The device has closed.
                    ::close( connectionFd );
                    ::close( deviceFd );
                    connectionFd = -1;
                    deviceFd = -1;
                } else if ( len > 0 ) {
                    writeAll( connectionFd, buffer, len );
                }
            }
        }
    }

    return 0;
}
/// <summary>
/// Vibrates the device for the specified milliseconds.
/// </summary>
/// <param name="milliseconds">The length to vibrate the device in milliseconds.</param>
/// <returns>int.</returns>
int Vibrate::vibrate(int milliseconds) {
	EPtr eptrs[] = { EPtr(MS, milliseconds) };
	return writeAll(SERVICE_VIBRATE, eptrs, 1);
}
Exemplo n.º 28
0
int main(int argc, char** args){
	FILE* file;
	_DECL_1DARRAY_BYTE(data);
	_DECL_DEALLOC(data);
	_DECL_1DARRAY_BYTE(compress_data);
	_DECL_DEALLOC(compress_data);
	FILE* writer;
	_DECL_1DARRAY_BYTE(decompress_data);
	_DECL_DEALLOC(decompress_data);
	void* _6;
	_DECL_DEALLOC(_6);
	_DECL_1DARRAY(_7);
	_DECL_DEALLOC(_7);
	_DECL_1DARRAY_BYTE(_8);
	_DECL_DEALLOC(_8);
	void* _10;
	_DECL_1DARRAY(_12);
	_DECL_DEALLOC(_12);
	void* _13;
	_DECL_1DARRAY(_15);
	_DECL_DEALLOC(_15);
	void* _16;
	int64_t _18;
	void* _19;
	_DECL_1DARRAY(_21);
	_DECL_DEALLOC(_21);
	_DECL_1DARRAY_BYTE(_22);
	_DECL_DEALLOC(_22);
	void* _23;
	_DECL_1DARRAY(_25);
	_DECL_DEALLOC(_25);
	void* _26;
	int64_t _28;
	void* _29;
	_DECL_1DARRAY(_31);
	_DECL_DEALLOC(_31);
	void* _32;
	_DECL_DEALLOC(_32);
	_DECL_1DARRAY(_33);
	_DECL_DEALLOC(_33);
	int64_t _34;
	_DECL_1DARRAY_BYTE(_37);
	_DECL_DEALLOC(_37);
	void* _38;
	_DECL_1DARRAY(_40);
	_DECL_DEALLOC(_40);
	void* _41;
	_DECL_1DARRAY(_43);
	_DECL_DEALLOC(_43);
	void* _44;
	int64_t _46;
	void* _47;
	_DECL_1DARRAY(_49);
	_DECL_DEALLOC(_49);
	//const %7 = [105,110,112,117,116,50,120,46,105,110] : int[]
	_DEALLOC(_7);
	_NEW_1DARRAY_int64_t(_7, 10, 0);
	_7[0] = 105; _7[1] = 110; _7[2] = 112; _7[3] = 117; _7[4] = 116; _7[5] = 50; _7[6] = 120; _7[7] = 46; _7[8] = 105; _7[9] = 110; 
	_ADD_DEALLOC(_7);
	//invoke (%6) = (%7) whiley/io/File:Reader : method(whiley/lang/ASCII:string)->(whiley/io/File:Reader)
	{
		_6 = Reader(_7, _7_size);
	}
	//assign %1 = %6  : {method()->(int) available,method()->() close,method()->(bool) hasMore,method(int)->(byte[]) read,method()->(byte[]) readAll}
	file = _6;
	//fieldload %9 = %1 readAll : {method()->(int) available,method()->() close,method()->(bool) hasMore,method(int)->(byte[]) read,method()->(byte[]) readAll}
	//indirectinvoke (%8) = %9 () : method()->(byte[])
	{
		_8 = readAll(file, &_8_size);
		_ADD_DEALLOC(_8);
	}
	//assign %2 = %8  : byte[]
	_DEALLOC(data);
	_COPY_1DARRAY_BYTE(data, _8);
	_ADD_DEALLOC(data);
	//fieldload %10 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %11 = %10 println_s : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//const %12 = [68,97,116,97,58,32,32,32,32,32,32,32,32,32] : int[]
	_DEALLOC(_12);
	_NEW_1DARRAY_int64_t(_12, 14, 0);
	_12[0] = 68; _12[1] = 97; _12[2] = 116; _12[3] = 97; _12[4] = 58; _12[5] = 32; _12[6] = 32; _12[7] = 32; _12[8] = 32; _12[9] = 32; _12[10] = 32; _12[11] = 32; _12[12] = 32; _12[13] = 32; 
	_ADD_DEALLOC(_12);
	//indirectinvoke () = %11 (%12) : method(int[])->()
	{
		println_s(_12, _12_size);
	}
	//fieldload %13 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %14 = %13 println_s : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//invoke (%15) = (%2) whiley/lang/ASCII:fromBytes : function(byte[])->(whiley/lang/ASCII:string)
	{
		_DEALLOC(_15);
		_15 = fromBytes(data, data_size);
		_15_size = data_size;
		_ADD_DEALLOC(_15);
	}
	//indirectinvoke () = %14 (%15) : method(int[])->()
	{
		println_s(_15, _15_size);
	}
	//fieldload %16 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %17 = %16 print : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//lengthof %18 = %2 : byte[]
	_18 = data_size;
	//indirectinvoke () = %17 (%18) : method(any)->()
	{
		printf("%"PRId64, _18);
	}
	//fieldload %19 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %20 = %19 println_s : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//const %21 = [32,98,121,116,101,115] : int[]
	_DEALLOC(_21);
	_NEW_1DARRAY_int64_t(_21, 6, 0);
	_21[0] = 32; _21[1] = 98; _21[2] = 121; _21[3] = 116; _21[4] = 101; _21[5] = 115; 
	_ADD_DEALLOC(_21);
	//indirectinvoke () = %20 (%21) : method(int[])->()
	{
		println_s(_21, _21_size);
	}
	//invoke (%22) = (%2) lz77_compress:compress : function(byte[])->(byte[])
	{
		void* tmp_data;
		_COPY_1DARRAY_PARAM(data, tmp_data, BYTE);
		_DEALLOC(_22);
		_22 = _compress_(tmp_data, data_size, true, _1DARRAYSIZE_PARAM_CALLBYREFERENCE(_22));
		_CALLEE_DEALLOC(data, "false-false-false" , "compress");
		_CALLEE_DEALLOC_POST(_22, data);
	}
	//assign %3 = %22  : byte[]
	_DEALLOC(compress_data);
	_COPY_1DARRAY_BYTE(compress_data, _22);
	_ADD_DEALLOC(compress_data);
	//fieldload %23 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %24 = %23 println_s : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//const %25 = [67,79,77,80,82,69,83,83,69,68,32,68,97,116,97,58,32,32,32] : int[]
	_DEALLOC(_25);
	_NEW_1DARRAY_int64_t(_25, 19, 0);
	_25[0] = 67; _25[1] = 79; _25[2] = 77; _25[3] = 80; _25[4] = 82; _25[5] = 69; _25[6] = 83; _25[7] = 83; _25[8] = 69; _25[9] = 68; _25[10] = 32; _25[11] = 68; _25[12] = 97; _25[13] = 116; _25[14] = 97; _25[15] = 58; _25[16] = 32; _25[17] = 32; _25[18] = 32; 
	_ADD_DEALLOC(_25);
	//indirectinvoke () = %24 (%25) : method(int[])->()
	{
		println_s(_25, _25_size);
	}
	//fieldload %26 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %27 = %26 print : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//lengthof %28 = %3 : byte[]
	_28 = compress_data_size;
	//indirectinvoke () = %27 (%28) : method(any)->()
	{
		printf("%"PRId64, _28);
	}
	//fieldload %29 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %30 = %29 println_s : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//const %31 = [32,98,121,116,101,115] : int[]
	_DEALLOC(_31);
	_NEW_1DARRAY_int64_t(_31, 6, 0);
	_31[0] = 32; _31[1] = 98; _31[2] = 121; _31[3] = 116; _31[4] = 101; _31[5] = 115; 
	_ADD_DEALLOC(_31);
	//indirectinvoke () = %30 (%31) : method(int[])->()
	{
		println_s(_31, _31_size);
	}
	//const %33 = [115,109,97,108,108,46,100,97,116] : int[]
	_DEALLOC(_33);
	_NEW_1DARRAY_int64_t(_33, 9, 0);
	_33[0] = 115; _33[1] = 109; _33[2] = 97; _33[3] = 108; _33[4] = 108; _33[5] = 46; _33[6] = 100; _33[7] = 97; _33[8] = 116; 
	_ADD_DEALLOC(_33);
	//invoke (%32) = (%33) whiley/io/File:Writer : method(whiley/lang/ASCII:string)->(whiley/io/File:Writer)
	{
		_32 = Writer(_33, _33_size);
	}
	//assign %4 = %32  : {method()->() close,method()->() flush,method(byte[])->(int) write,...}
	writer = _32;
	//fieldload %35 = %4 write : {method()->() close,method()->() flush,method(byte[])->(int) write,...}
	//indirectinvoke (%34) = %35 (%3) : method(byte[])->(int)
	{
		writeAll(writer, compress_data, compress_data_size);
	}
	//fieldload %36 = %4 close : {method()->() close,method()->() flush,method(byte[])->(int) write,...}
	//indirectinvoke () = %36 () : method()->()
	{
		fclose(writer);
		writer = NULL;
	}
	//invoke (%37) = (%3) lz77_compress:decompress : function(byte[])->(byte[])
	{
		void* tmp_data;
		_COPY_1DARRAY_PARAM(compress_data, tmp_data, BYTE);
		_DEALLOC(_37);
		_37 = _decompress_(tmp_data, compress_data_size, true, _1DARRAYSIZE_PARAM_CALLBYREFERENCE(_37));
		_CALLEE_DEALLOC(compress_data, "false-false-false" , "decompress");
		_CALLEE_DEALLOC_POST(_37, compress_data);
	}
	//assign %5 = %37  : byte[]
	_DEALLOC(decompress_data);
	_COPY_1DARRAY_BYTE(decompress_data, _37);
	_ADD_DEALLOC(decompress_data);
	//fieldload %38 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %39 = %38 println_s : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//const %40 = [68,69,67,79,77,80,82,69,83,83,69,68,58,32,32,32] : int[]
	_DEALLOC(_40);
	_NEW_1DARRAY_int64_t(_40, 16, 0);
	_40[0] = 68; _40[1] = 69; _40[2] = 67; _40[3] = 79; _40[4] = 77; _40[5] = 80; _40[6] = 82; _40[7] = 69; _40[8] = 83; _40[9] = 83; _40[10] = 69; _40[11] = 68; _40[12] = 58; _40[13] = 32; _40[14] = 32; _40[15] = 32; 
	_ADD_DEALLOC(_40);
	//indirectinvoke () = %39 (%40) : method(int[])->()
	{
		println_s(_40, _40_size);
	}
	//fieldload %41 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %42 = %41 println_s : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//invoke (%43) = (%5) whiley/lang/ASCII:fromBytes : function(byte[])->(whiley/lang/ASCII:string)
	{
		_DEALLOC(_43);
		_43 = fromBytes(decompress_data, decompress_data_size);
		_43_size = decompress_data_size;
		_ADD_DEALLOC(_43);
	}
	//indirectinvoke () = %42 (%43) : method(int[])->()
	{
		println_s(_43, _43_size);
	}
	//fieldload %44 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %45 = %44 print : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//lengthof %46 = %5 : byte[]
	_46 = decompress_data_size;
	//indirectinvoke () = %45 (%46) : method(any)->()
	{
		printf("%"PRId64, _46);
	}
	//fieldload %47 = %0 out : {int[][] args,{method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s} out}
	//fieldload %48 = %47 println_s : {method(any)->() print,method(int[])->() print_s,method(any)->() println,method(int[])->() println_s}
	//const %49 = [32,98,121,116,101,115] : int[]
	_DEALLOC(_49);
	_NEW_1DARRAY_int64_t(_49, 6, 0);
	_49[0] = 32; _49[1] = 98; _49[2] = 121; _49[3] = 116; _49[4] = 101; _49[5] = 115; 
	_ADD_DEALLOC(_49);
	//indirectinvoke () = %48 (%49) : method(int[])->()
	{
		println_s(_49, _49_size);
	}
	//return
	if(file != NULL){fclose(file); file = NULL;}
	_DEALLOC(data);
	_DEALLOC(compress_data);
	if(writer != NULL){fclose(writer); writer = NULL;}
	_DEALLOC(decompress_data);
	_DEALLOC(_7);
	_DEALLOC(_8);
	_DEALLOC(_12);
	_DEALLOC(_15);
	_DEALLOC(_21);
	_DEALLOC(_22);
	_DEALLOC(_25);
	_DEALLOC(_31);
	_DEALLOC(_33);
	_DEALLOC(_37);
	_DEALLOC(_40);
	_DEALLOC(_43);
	_DEALLOC(_49);
	exit(0);
}
Exemplo n.º 29
0
int eHttpStream::openUrl(const std::string &url, std::string &newurl)
{
	int port;
	std::string hostname;
	std::string uri = url;
	std::string request;
	size_t buflen = 1024;
	char *linebuf = NULL;
	int result;
	char proto[100];
	int statuscode = 0;
	char statusmsg[100];
	bool playlist = false;
	bool contenttypeparsed = false;

	close();

	std::string user_agent = "Enigma2 HbbTV/1.1.1 (+PVR+RTSP+DL;OpenBh;;;)";
	std::string extra_headers = "";
	size_t pos = uri.find('#');
	if (pos != std::string::npos)
	{
		extra_headers = uri.substr(pos + 1);
		uri = uri.substr(0, pos);

		pos = extra_headers.find("User-Agent=");
		if (pos != std::string::npos)
		{
			size_t hpos_start = pos + 11;
			size_t hpos_end = extra_headers.find('&', hpos_start);
			if (hpos_end != std::string::npos)
				user_agent = extra_headers.substr(hpos_start, hpos_end - hpos_start);
			else
				user_agent = extra_headers.substr(hpos_start);
		}
	}

	int pathindex = uri.find("/", 7);
	if (pathindex > 0)
	{
		hostname = uri.substr(7, pathindex - 7);
		uri = uri.substr(pathindex, uri.length() - pathindex);
	}
	else
	{
		hostname = uri.substr(7, uri.length() - 7);
		uri = "/";
	}
	int authenticationindex = hostname.find("@");
	if (authenticationindex > 0)
	{
		authorizationData =  base64encode(hostname.substr(0, authenticationindex));
		hostname = hostname.substr(authenticationindex + 1);
	}
	int customportindex = hostname.find(":");
	if (customportindex > 0)
	{
		port = atoi(hostname.substr(customportindex + 1, hostname.length() - customportindex - 1).c_str());
		hostname = hostname.substr(0, customportindex);
	}
	else if (customportindex == 0)
	{
		port = atoi(hostname.substr(1, hostname.length() - 1).c_str());
		hostname = "localhost";
	}
	else
	{
		port = 80;
	}

	streamSocket = Connect(hostname.c_str(), port, 10);
	if (streamSocket < 0)
		goto error;

	request = "GET ";
	request.append(uri).append(" HTTP/1.1\r\n");
	request.append("Host: ").append(hostname).append("\r\n");
	request.append("User-Agent: ").append(user_agent).append("\r\n");
	if (authorizationData != "")
	{
		request.append("Authorization: Basic ").append(authorizationData).append("\r\n");
	}

	pos = 0;
	while (pos != std::string::npos && !extra_headers.empty())
	{
		std::string name, value;
		size_t start = pos;
		size_t len = std::string::npos;
		pos = extra_headers.find('=', pos);
		if (pos != std::string::npos)
		{
			len = pos - start;
			pos++;
			name = extra_headers.substr(start, len);
			start = pos;
			len = std::string::npos;
			pos = extra_headers.find('&', pos);
			if (pos != std::string::npos)
			{
				len = pos - start;
				pos++;
			}
			value = extra_headers.substr(start, len);
		}
		if (!name.empty() && !value.empty())
		{
			if (name.compare("User-Agent") == 0)
				continue;
			eDebug("[eHttpStream] setting extra-header '%s:%s'", name.c_str(), value.c_str());
			request.append(name).append(": ").append(value).append("\r\n");
		}
		else
		{
			eDebug("[eHttpStream] Invalid header format %s", extra_headers.c_str());
			break;
		}
	}

	request.append("Accept: */*\r\n");
	request.append("Connection: close\r\n");
	request.append("\r\n");

	writeAll(streamSocket, request.c_str(), request.length());

	linebuf = (char*)malloc(buflen);

	result = readLine(streamSocket, &linebuf, &buflen);
	if (result <= 0)
		goto error;

	result = sscanf(linebuf, "%99s %d %99s", proto, &statuscode, statusmsg);
	if (result != 3 || (statuscode != 200 && statuscode != 206 && statuscode != 302))
	{
		eDebug("[eHttpStream] %s: wrong http response code: %d", __func__, statuscode);
		goto error;
	}

	while (1)
	{
		result = readLine(streamSocket, &linebuf, &buflen);
		if (!contenttypeparsed)
		{
			char contenttype[33];
			if (sscanf(linebuf, "Content-Type: %32s", contenttype) == 1)
			{
				contenttypeparsed = true;
				if (!strcasecmp(contenttype, "application/text")
				|| !strcasecmp(contenttype, "audio/x-mpegurl")
				|| !strcasecmp(contenttype, "audio/mpegurl")
				|| !strcasecmp(contenttype, "application/m3u"))
				{
					/* assume we'll get a playlist, some text file containing a stream url */
					playlist = true;
				}
				continue;
			}
		}
		if (playlist && !strncasecmp(linebuf, "http://", 7))
		{
			newurl = linebuf;
			eDebug("[eHttpStream] %s: playlist entry: %s", __func__, newurl.c_str());
			break;
		}
		if (((statuscode == 301) || (statuscode == 302) || (statuscode == 303) || (statuscode == 307) || (statuscode == 308)) &&
				strncasecmp(linebuf, "location: ", 10) == 0)
		{
			newurl = &linebuf[10];
			if (!extra_headers.empty())
				newurl.append("#").append(extra_headers);
			eDebug("[eHttpStream] %s: redirecting to: %s", __func__, newurl.c_str());
			break;
		}

		if (((statuscode == 200) || (statuscode == 206)) && !strncasecmp(linebuf, "transfer-encoding: chunked", strlen("transfer-encoding: chunked")))
		{
			isChunked = true;
		}
		if (!playlist && result == 0)
			break;
		if (result < 0)
			break;
	}

	free(linebuf);
	return 0;
error:
	eDebug("[eHttpStream] %s failed", __func__);
	free(linebuf);
	close();
	return -1;
}
int main(int argc, char *argv[])
{
	char buffer[4096];
	int fd;
	long long size;
	if (argc < 3)
	{
		printf("usage: %s <volumename> <filename> [<size>]\n", argv[0]);
		exit(EXIT_FAILURE);
	}
	if (argc < 4)
	{
		struct stat st;
		if (stat(argv[2], &st) < 0)
		{
			std::cerr << "failed to open " << argv[2] << std::endl;
			exit(EXIT_FAILURE);
		}
		size = st.st_size;
	}
	else
	{
		size = atoi(argv[3]);
	}
	int volumeid = find_volumeid(argv[1]);
	if (volumeid >= 0)
	{
		std::cout << "found existing volume, resize to " << size << std::endl;
		int ret;
		struct ubi_rsvol_req req;
		fd = open("/dev/ubi0", O_RDONLY);
		if (fd < 0)
		{
			std::cerr << "failed to open " << "/dev/ubi0" <<  std::endl;
			exit(EXIT_FAILURE);
		}
		req.bytes = size;
		req.vol_id = volumeid;
		ret = ioctl(fd, UBI_IOCRSVOL, &req);
		close(fd);
	}
	else
	{
		std::cout << "create new volume, size " << size << std::endl;
		int ret;
		struct ubi_mkvol_req r;
		size_t n;

		memset(&r, 0, sizeof(struct ubi_mkvol_req));

		r.vol_id = UBI_VOL_NUM_AUTO;
		r.alignment = 1;
		r.bytes = size;
		r.vol_type = UBI_STATIC_VOLUME;

		n = strlen(argv[1]);
		if (n > UBI_MAX_VOLUME_NAME)
		{
			std::cerr << "volume name too long, max " << UBI_MAX_VOLUME_NAME << std::endl;
			exit(EXIT_FAILURE);
		}

		strncpy(r.name, argv[1], UBI_MAX_VOLUME_NAME + 1);
		r.name_len = n;

		fd = open("/dev/ubi0", O_RDONLY);
		if (fd < 0)
		{
			std::cerr << "failed to open " << "/dev/ubi0" <<  std::endl;
			exit(EXIT_FAILURE);
		}

		ret = ioctl(fd, UBI_IOCMKVOL, &r);
		if (ret < 0) 
		{
			close(fd);
			std::cerr << "failed to create volume" <<  std::endl;
			exit(EXIT_FAILURE);
		}

		close(fd);
		volumeid = r.vol_id;
		for (int i = 0; i < 10; i++)
		{
			snprintf(buffer, sizeof(buffer), "/dev/ubi0_%d", volumeid);
			if (access(buffer, F_OK) >= 0) break;
			/* HACK: give udev/mdev some time to create the devicenode */
			usleep(100000);
		}
	}
	snprintf(buffer, sizeof(buffer), "/dev/ubi0_%d", volumeid);
	fd = open(buffer, O_RDWR);
	if (fd < 0)
	{
		std::cerr << "failed to open " << buffer <<  std::endl;
		exit(EXIT_FAILURE);
	}
	ioctl(fd, UBI_IOCVOLUP, &size);
	int in;
	if (!strcmp(argv[2], "-"))
	{
		in = 0;
	}
	else
	{
		in = open(argv[2], O_RDONLY);
	}
	if (in < 0)
	{
		std::cerr << "failed to open " << argv[2] <<  std::endl;
		exit(EXIT_FAILURE);
	}
	while (1)
	{
		int result = timedRead(in, buffer, sizeof(buffer), 5000, 5000);
		if (result <= 0) break;
		if (writeAll(fd, buffer, result) < 0) break;
	}
	exit(EXIT_SUCCESS);
}