size_t StdCompilerINIRead::GetStringLength(RawCompileType eRawType)
{
	// Excpect valid position
	if (!pPos)
		{ notFound("String"); return 0; }
	// Skip whitespace
	SkipWhitespace();
	// Save position
	const char *pStart = pPos;
	// Escaped? Go over '"'
	if (eRawType == RCT_Escaped && *pPos++ != '"')
		{ notFound("Escaped string"); return 0; }
	// Search end of string
	size_t iLength = 0;
	while (!TestStringEnd(eRawType))
	{
		// Read a character (we're just counting atm)
		if (eRawType == RCT_Escaped)
			ReadEscapedChar();
		else
			pPos++;
		// Count it
		iLength++;
	}
	// Reset position, return the length
	pPos = pStart;
	return iLength;
}
Пример #2
0
int main() {
    while (1) {
        puts("shell> ");
        char* in = gets();
        char **args = 0;

        if (in == 0) goto done;

        args = split(in);
        if (args == 0) goto done;
        
        char *cmd = args[0];
        if (cmd == 0) goto done;

        int fd = open(cmd);
        if (fd < 0) {
            notFound(cmd);
            goto done;
        }

        int magic = 0;
        readFully(fd,&magic,4);
     
        if (magic == 0x464c457f) {
            /* executable file */
            close(fd);

            long id = fork();
            if (id == 0) {
                /* child */
                long rc = execv(cmd,args);
                notFound(cmd);
                exit(rc);
            } else {
                join(id);
            }
        } else {
            /* write it */
            seek(fd,0);
            char buf[100];
            while (1) {
                int n = read(fd,buf,100);
                if (n == 0) break;
                if (n < 0) {
                    notFound(cmd);
                    break;
                }
                for (int j=0; j<n; j++) {
                    putchar(buf[j]);
                }
            }
            close(fd);
        }
done:
        if (in) free(in);
        if (args) free(args);
    }
    return 0;
}
void StdCompilerINIRead::Boolean(bool &rBool)
{
	if (!pPos) { notFound("Boolean"); return; }
	if (*pPos == '1' && !isdigit((unsigned char)*(pPos+1)))
		{ rBool = true; pPos ++; }
	else if (*pPos == '0' && !isdigit((unsigned char)*(pPos+1)))
		{ rBool = false; pPos ++; }
	else if (SEqual2(pPos, "true"))
		{ rBool = true; pPos += 4; }
	else if (SEqual2(pPos, "false"))
		{ rBool = false; pPos += 5; }
	else
		{ notFound("Boolean"); return; }
}
StdBuf StdCompilerINIRead::ReadString(size_t iLength, RawCompileType eRawType, bool fAppendNull)
{
	// Excpect valid position
	if (!pPos)
		{ notFound("String"); return StdBuf(); }
	// Skip whitespace
	SkipWhitespace();
	// Escaped? Go over '"'
	if (eRawType == RCT_Escaped && *pPos++ != '"')
		{ notFound("Escaped string"); return StdBuf(); }
	// Create buffer
	StdBuf OutBuf; OutBuf.New(iLength + (fAppendNull ? sizeof('\0') : 0));
	// Read
	char *pOut = getMBufPtr<char>(OutBuf);
	while (iLength && !TestStringEnd(eRawType))
	{
		// Read a character
		if (eRawType == RCT_Escaped)
			*pOut++ = ReadEscapedChar();
		else
			*pOut++ = *pPos++;
		// Count it
		iLength--;
	}
	// Escaped: Go over '"'
	if (eRawType == RCT_Escaped)
	{
		while (*pPos != '"')
		{
			if (!*pPos || *pPos == '\n' || *pPos == '\r')
			{
				Warn("string not terminated!");
				pPos--;
				break;
			}
			pPos++;
		}
		pPos++;
	}
	// Nothing read? Identifiers need to be non-empty
	if (pOut == OutBuf.getData() && (eRawType == RCT_Idtf || eRawType == RCT_ID))
		{ notFound("String"); return StdBuf(); }
	// Append null
	if (fAppendNull)
		*pOut = '\0';
	// Shrink, if less characters were read
	OutBuf.Shrink(iLength);
	// Done
	return OutBuf;
}
Пример #5
0
void Render::Html::contest(int cid){
    Contest c(cid);
    if(!c) return notFound("Contest");
    header(c.name());
    o << "<h2>" + escape(c.name()) + "</h2>"
         "<div class=\"contest\">";
    std::string descr = c.getDescription();
    if(!descr.empty())
        o << "<div class=\"description\">" << descr << "</div>";
    o << "<h3 id=\"submissions\">" << icon("disc") << " Submissions</h3>";
    std::vector<Track> tracks = c.submissions();
    submissions(c, tracks);
    if(Session::user() && c.state()==Contest::Submissions){
        std::vector<Track> utracks = Session::user().tracks();
        std::vector<Track> toSubmit;
        for(std::vector<Track>::const_iterator i=utracks.begin(); i!=utracks.end(); i++){
            if(std::find(tracks.begin(),tracks.end(),*i)==tracks.end())
                toSubmit.push_back(*i);
        }
        if(!toSubmit.empty()){
            o << "<form action=\"" + c.url() + "/submit\" method=\"post\">"
                 "Submit a track : "
                 "<select name=\"tid\">";
            for(std::vector<Track>::const_iterator i=toSubmit.begin(); i!=toSubmit.end(); i++)
                o << "<option value=\"" << number(i->id()) << "\">" << escape(i->title()) << "</option>";
            o << "</select>"
                 " <input type=\"submit\" value=\"Submit\" />"
                 "</form>";
        }
    }
    o << "</div>";
    footer();
}
Пример #6
0
bool HttpResponse::sendFile(String fileName, bool allowGzipFileCheck /* = true*/)
{
	if (stream != NULL)
	{
		SYSTEM_ERROR("Stream already created");
		delete stream;
		stream = NULL;
	}

	String compressed = fileName + ".gz";
	if (allowGzipFileCheck && fileExist(compressed))
	{
		debugf("found %s", compressed.c_str());
		stream = new FileStream(compressed);
		setHeader("Content-Encoding", "gzip");
	}
	else if (fileExist(fileName))
	{
		debugf("found %s", fileName.c_str());
		stream = new FileStream(fileName);
	}
	else
	{
		notFound();
		return false;
	}

	if (!hasHeader("Content-Type"))
	{
		const char *mime = ContentType::fromFullFileName(fileName);
		if (mime != NULL)
			setContentType(mime);
	}
	return true;
}
Пример #7
0
bool HttpResponse::sendTemplate(TemplateFileStream* newTemplateInstance)
{
	if (stream != NULL)
	{
		SYSTEM_ERROR("Stream already created");
		delete stream;
		stream = NULL;
	}

	stream = newTemplateInstance;
	if (!newTemplateInstance->fileExist())
	{
		notFound();
		delete stream;
		stream = NULL;
		return false;
	}

	if (!hasHeader("Content-Type"))
	{
		const char *mime = ContentType::fromFullFileName(newTemplateInstance->fileName());
		if (mime != NULL)
			setContentType(mime);
	}
	return true;
}
unsigned long StdCompilerINIRead::ReadUNum()
{
	if (!pPos)
		{ notFound("Number"); return 0; }
	// Skip whitespace
	SkipWhitespace();
	// Read number. If this breaks, Günther is to blame!
	const char *pnPos = pPos;
	unsigned long iNum = strtoul(pPos, const_cast<char **>(&pnPos), 10);
	// Could not read?
	if (!iNum && pnPos == pPos)
		{ notFound("Number"); return 0; }
	// Get over it
	pPos = pnPos;
	return iNum;
}
Пример #9
0
void TagLibTagReader::metaDataChanged()
{
	if(d->metaData().isEmpty())
	{
		emit notFound(d->currentSource());
		return;
	}

	const QString artist = d->getTag<QString>("ARTIST", tr("Unknown"));
	const QString artistSort = d->getTag<QString>("ARTIST-SORT", artist);
	const QString albumName = d->getTag<QString>("ALBUM", tr("No Album Title"));
	const QString title = d->getTag<QString>("TITLE", tr("No Track Title"));
	const qint8 trackNumber = d->getTag<quint8>("TRACK-NUMBER", 0);
	const qreal trackReplayGain = d->getTag<qreal>("REPLAYGAIN-TRACK-GAIN", -10000);
	const qreal albumReplayGain = d->getTag<qreal>("REPLAYGAIN-ALBUM-GAIN", trackReplayGain);
	const QString mbid = d->getTag<QString>("MUSICBRAINZ-TRACK-ID", QString());
	emit finished(
		Jerboa::TrackData(
			d->currentSource(),
			albumName,
			QString(),
			QString(),
			artist,
			artistSort,
			title,
			trackNumber,
			albumReplayGain,
			trackReplayGain,
			mbid
		)
	);
}
Пример #10
0
/* Serve downloadable file. */
void serveDownloadableFile(int client, const char *filename, const char *displayFilename, const char * type)
{

	FILE *resource = NULL;
	char buf[1024];
	size_t len;

	STATIC_SEND(client, "HTTP/1.0 200 OK\r\n", 0);
	STATIC_SEND(client, SERVER_STRING, 0);

	len = snprintf(buf, sizeof(buf), "Content-Type: %s\r\n",type);
	send(client, buf, len, 0);

	len = snprintf(buf, sizeof(buf), "Content-Disposition: attachment; filename=\"%s\"\r\n",displayFilename);
	send(client, buf, len, 0);

	STATIC_SEND(client, "\r\n", 0);

	resource = fopen(filename, "r");
	if (resource == NULL)
		notFound(client);
	else
	{
		cat(client, resource);
	}
	fclose(resource);
}
Пример #11
0
HRESULT CKhParser::saveResults(void)
{
//    char locale_name[32] = "";
//    locale_name[0] = '.';
//    _ui64toa_s(1251, locale_name + 1, sizeof(locale_name) - 1, 10);
    std::locale loc = std::locale(std::locale("C"), new std::codecvt_utf8<wchar_t, 0x10ffff, std::generate_header>());
    // print words parsed
    if (dict.length() != 0 && cache.size() != 0) {
        std::wofstream outDict(dict, std::wofstream::binary);
        if (outDict.is_open()) {
//            std::locale loc;
//            loc = std::locale("ru_RU.utf8");
            outDict.imbue(loc);

//            outDict.imbue(loc);//locale_name));
            HomMap::iterator it = cache.begin();
            for (; it != cache.end(); ++it) {
                outDict.write(it->first.c_str(), it->first.length());// * sizeof(wchar_t));
                outDict.write(L":\t", wcslen(L":\t"));// * sizeof(wchar_t));
                wchar_t count[10] = L"";
                _itow_s(it->second.count, count, 10, 10);
//                wsprintf((LPSTR)count, (LPCSTR)L"%d", it->second.count);
                outDict.write(count, wcslen(count));// * sizeof(wchar_t));// << L": \t" << it->second.count << L"\t";
                outDict.write(L":\t", wcslen(L":\t"));// * sizeof(wchar_t));
                HomVct::iterator vt = it->second.homVct.begin();
                for (; vt != it->second.homVct.end(); ++vt) {
                    outDict.write(vt->khak.c_str(), vt->khak.length());// * sizeof(wchar_t));
                    outDict.write(L" : ", wcslen(L" : "));// * sizeof(wchar_t));
                    outDict.write(vt->rus.c_str(), vt->rus.length());// * sizeof(wchar_t));
                    outDict.write(L"; ", wcslen(L"; "));// * sizeof(wchar_t));
    //                outDict << vt->khak << L" : " << vt->rus << L" ; ";
                }
                outDict.write(L"\n", wcslen(L"\n"));// * sizeof(wchar_t));
    //            outDict << L"\n";
            }
        }
        outDict.close();
    }
    // print words not found
    if (notfound.length() != 0 && empty.size() != 0) {
        std::wofstream notFound(notfound, std::wofstream::binary);
        if (notFound.is_open()) {
            notFound.imbue(loc);
            std::map<std::wstring, int>::iterator et = empty.begin();
            for (; et != empty.end(); ++et) {
                notFound.write(et->first.c_str(), et->first.length());
                notFound.write(L" : ", wcslen(L" : "));// * sizeof(wchar_t));
                wchar_t count[10] = L"";
                _itow_s(et->second, count, 10, 10);
//                wsprintf((LPSTR)count, (LPCSTR)L"%d", et->second);
                notFound.write(count, wcslen(count));// * sizeof(wchar_t));// << L": \t" << it->second.count << L"\t";
                notFound.write(L"\n", wcslen(L"\n"));// * sizeof(wchar_t));
//                notFound << et->first << L" : " << et->second << L"\n";
            }
            notFound.close();
        }
    }
    return S_OK;
}
Пример #12
0
void MainWindow::on_pushButton_Drawing_clicked()
{
    QString fileNumber;
    fileNumber = ui->lineEdit_FindPart->text();

    int partNumber = fileNumber.toInt();
    int directoryMin = (partNumber /1000)* (1000) + 1;// rounding number
    int directoryMax = directoryMin + 999;

    if(fileNumber == "0")
    {

        QMessageBox::information(this, "Enter a valid number", "Enter a number other than 0");
    }
    else if(fileNumber == "")
    {

        QMessageBox::information(this, "Empty", "Enter a number");
    }
    else if (partNumber <= 10000)// if part number is between 1 and 10000 use the static directory AND ADD DASH (-)
    {
        searchingFiles();
        //static directory
        QString directoryRange = "B-0001-B10000";
        // assigned to a variable to be able to check the status
        bool linkToDrawing = QDesktopServices::openUrl(QUrl("file:///N:/SolidWorksDrawing/B---/" + directoryRange + "/B-" + fileNumber + ".slddrw") );

        if(linkToDrawing !=true)
        {
            notFoundLessThan();
            QMessageBox::information(this, "Not Found", "The drawing you are looking for was not found in this directory");
        }
        else
        {
            foundItLessThan();
        }

    }

    else
    {
        searchingFiles();
        //converting ints to strings and concatinating them
        QString directoryRange = "B"+ QString::number(directoryMin)+ "-" + "B" + QString::number(directoryMax);
        bool linkToDrawing = QDesktopServices::openUrl(QUrl("file:///N:/SolidWorksDrawing/B---/" + directoryRange + "/b" + fileNumber + ".slddrw") );

        if(linkToDrawing !=true)
        {
            notFound();
            QMessageBox::information(this, "Not Found", "The drawing you are looking for was not found in this directory");
        }
        else
        {
            foundIt();
        }

    }

}
Пример #13
0
void MainWindow::on_pushButton_Pdf_clicked()
{
    QString fileNumber;
    fileNumber = ui->lineEdit_FindPart->text();

    int partNumber = fileNumber.toInt();

    if(fileNumber == "" )
    {

        QMessageBox::information(this, "Empty", "Enter a number");
    }

    else if(fileNumber == "0" )
    {

        QMessageBox::information(this, "Enter a valid number", "Enter a number other than 0");
    }
    else if (partNumber <= 10000) // IF PART LESS THAN 10000, ADD DASH (-)
    {
        searchingFiles();
        // assigned to a variable to be able to check the status
        bool linkToPdf = QDesktopServices::openUrl(QUrl("file:///P:/S_Works-Dwgs/B---/B-" + fileNumber + ".pdf") );

        if(linkToPdf!= true)
        {
            notFoundLessThan();
            QMessageBox::information(this, "Not Found", "The PDF you are looking for was not found in this directory");
        }
        else
        {
            foundItLessThan();
        }

    }

    else
    {
        searchingFiles();
        // assigned to a variable to be able to check the status
        bool linkToPdf = QDesktopServices::openUrl(QUrl("file:///P:/S_Works-Dwgs/B---/B" + fileNumber + ".pdf") );

        if(linkToPdf!= true)
        {
            notFound();
            QMessageBox::information(this, "Not Found", "The PDF you are looking for was not found in this directory");
        }
        else
        {
            foundIt();
        }
    }

}
void DatabaseOpenWidget::showEvent(QShowEvent* event)
{
    DialogyWidget::showEvent(event);
    m_ui->editPassword->setFocus();

#ifdef WITH_XC_YUBIKEY
    // showEvent() may be called twice, so make sure we are only polling once
    if (!m_yubiKeyBeingPolled) {
        // clang-format off
        connect(YubiKey::instance(), SIGNAL(detected(int,bool)), SLOT(yubikeyDetected(int,bool)), Qt::QueuedConnection);
        connect(YubiKey::instance(), SIGNAL(detectComplete()), SLOT(yubikeyDetectComplete()), Qt::QueuedConnection);
        connect(YubiKey::instance(), SIGNAL(notFound()), SLOT(noYubikeyFound()), Qt::QueuedConnection);
        // clang-format on

        pollYubikey();
        m_yubiKeyBeingPolled = true;
    }
#endif
}
Пример #15
0
void *MSHashTable::lookup(const char *key_) const
{
  MSHashEntry *entry=(key_!=0)?searchBucketFor(bucket(hash(key_)),key_):0;
  if (entry==0) return (void *)notFound();
  else return entry->value();
}
Пример #16
0
void StdCompilerINIRead::Character(char &rChar)
{
	if (!pPos || !isalpha((unsigned char)*pPos))
		{ notFound("Character"); return; }
	rChar = *pPos++;
}
Пример #17
0
void run(void) {
    hook("run() called inside missing-import.");
    notFound();
}
Пример #18
0
Playlist::Widget::Widget( QWidget* parent )
        : KVBox( parent )
{
    setContentsMargins( 1, 1, 1, 1 );

    m_searchWidget = new ProgressiveSearchWidget( this );

    //this is really only useful for debugging at the moment, so dont show it to users and testers
    /*m_sortBox = new QComboBox( this );
    m_sortBox->insertItem( 0, "Album", Album);
    m_sortBox->insertItem( 1, "AlbumArtist", Album);
    m_sortBox->insertItem( 2, "Artist", Artist );
    m_sortBox->insertItem( 3, "Bitrate", Bitrate );
    m_sortBox->insertItem( 4, "Bpm", Bpm );
    m_sortBox->insertItem( 5, "Comment", Comment );
    m_sortBox->insertItem( 6, "Composer", Composer );
    m_sortBox->insertItem( 7, "Directory", Directory );
    m_sortBox->insertItem( 8, "DiscNumber", DiscNumber );
    m_sortBox->insertItem( 9, "Filename", Filename );
    m_sortBox->insertItem( 10, "Filesize", Filesize );
    m_sortBox->insertItem( 11, "Genre", Genre );
    m_sortBox->insertItem( 12, "LastPlayed", LastPlayed );
    m_sortBox->insertItem( 13, "Length", Length );
    m_sortBox->insertItem( 14, "Mood", Mood );
    m_sortBox->insertItem( 15, "PlayCount", PlayCount );
    m_sortBox->insertItem( 16, "Rating", Rating );
    m_sortBox->insertItem( 17, "SampleRate", SampleRate );
    m_sortBox->insertItem( 18, "Score", Score );
    m_sortBox->insertItem( 29, "Source", Source );
    m_sortBox->insertItem( 30, "Title", Title );
    m_sortBox->insertItem( 31, "TrackNumber", TrackNumber );
    m_sortBox->insertItem( 32, "Type", Type );
    m_sortBox->insertItem( 33, "Year", Year );

    connect( m_sortBox, SIGNAL( activated( int ) ), this, SLOT( sort( int ) ) );*/
    
    QWidget * layoutHolder = new QWidget( this );

    QVBoxLayout* mainPlaylistlayout = new QVBoxLayout( layoutHolder );
    mainPlaylistlayout->setContentsMargins( 0, 0, 0, 0 );

    m_playlistView = new PrettyListView( this );
    m_playlistView->show();

    connect( m_searchWidget, SIGNAL( filterChanged( const QString &, int, bool ) ), m_playlistView, SLOT( find( const QString &, int, bool ) ) );
    connect( m_searchWidget, SIGNAL( next( const QString &, int ) ), m_playlistView, SLOT( findNext( const QString &, int ) ) );
    connect( m_searchWidget, SIGNAL( previous( const QString &, int ) ), m_playlistView, SLOT( findPrevious( const QString &, int ) ) );
    connect( m_searchWidget, SIGNAL( filterCleared() ), m_playlistView, SLOT( clearSearchTerm() ) );
    connect( m_searchWidget, SIGNAL( showOnlyMatches( bool ) ), m_playlistView, SLOT( showOnlyMatches( bool ) ) );
    connect( m_searchWidget, SIGNAL( activateFilterResult() ), m_playlistView, SLOT( playFirstSelected() ) );
    connect( m_searchWidget, SIGNAL( downPressed() ), m_playlistView, SLOT( setFocus() ) );

    connect( m_playlistView, SIGNAL( found() ), m_searchWidget, SLOT( match() ) );
    connect( m_playlistView, SIGNAL( notFound() ), m_searchWidget, SLOT( noMatch() ) );

    connect( LayoutManager::instance(), SIGNAL( activeLayoutChanged() ), m_playlistView, SLOT( reset() ) );

    mainPlaylistlayout->setSpacing( 0 );
    mainPlaylistlayout->addWidget( m_playlistView );

    KHBox *barBox = new KHBox( this );
    barBox->setMargin( 0 );

    KToolBar *plBar = new Amarok::ToolBar( barBox );
    plBar->setObjectName( "PlaylistToolBar" );

    Model::instance();

    // the Controller ctor creates the undo/redo actions that we use below, so we want
    // to make sure that it's been constructed and the the actions registered
    Controller::instance();

    {
        //START Playlist toolbar
        plBar->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Preferred );
        plBar->setIconDimensions( 22 );
        plBar->setMovable( false );
        plBar->addAction( new KToolBarSpacerAction( this ) );

        plBar->addAction( Amarok::actionCollection()->action( "playlist_clear" ) );
        
        //FIXME this action should go in ActionController, but we don't have any visibility to the view
        KAction *action = new KAction( KIcon( "music-amarok" ), i18n("Show active track"), this );
        connect( action, SIGNAL( triggered( bool ) ), m_playlistView, SLOT( scrollToActiveTrack() ) );
        plBar->addAction( action );

        plBar->addSeparator();
        plBar->addAction( Amarok::actionCollection()->action( "playlist_undo" ) );
        plBar->addAction( Amarok::actionCollection()->action( "playlist_redo" ) );
        plBar->addSeparator();
        plBar->addAction( Amarok::actionCollection()->action( "playlist_save" ) );
        plBar->addAction( Amarok::actionCollection()->action( "playlist_export" ) );
        plBar->addSeparator();

        Playlist::LayoutConfigAction *layoutConfigAction = new Playlist::LayoutConfigAction( this );
        plBar->addAction( layoutConfigAction );
        QToolButton *tbutton = qobject_cast<QToolButton*>(plBar->widgetForAction( layoutConfigAction ) );
        if( tbutton )
            tbutton->setPopupMode( QToolButton::InstantPopup );

        plBar->addAction( new KToolBarSpacerAction( this ) );

    } //END Playlist Toolbar

    setFrameShape( QFrame::StyledPanel );
    setFrameShadow( QFrame::Sunken );
}
Пример #19
0
int EventStreamingServer::svc(void)
{
	ACE_Time_Value timeout;
	char buf[2048];
	CStdString logMsg;
	CStdString sessionId;
	int messagesSent = 0;

	ssize_t size = peer().recv(buf, 2040);

	if(size <= 5)
	{
		CStdString notFound("HTTP/1.0 404 not found\r\nContent-type: text/html\r\n\r\nNot found\r\n");
		peer().send(notFound, notFound.GetLength(), MSG_NOSIGNAL);
		return 0;
	}

	try
	{
		int startUrlOffset = 5;
		char* stopUrl = ACE_OS::strstr(buf+startUrlOffset, " HTTP");

		if(!stopUrl)
		{
			throw (CStdString("Malformed http request"));
		}

		CStdString header;
		struct tm date = {0};
		time_t now = time(NULL);
		CStdString rfc822Date;

		ACE_OS::gmtime_r(&now, &date);
		rfc822Date.Format("Tue, %.2d Nov %.4d %.2d:%.2d:%.2d GMT", date.tm_mday, (date.tm_year+1900), date.tm_hour, date.tm_min, date.tm_sec);
		header.Format("HTTP/1.1 200 OK\r\nLast-Modified:%s\r\nContent-Type:text/plain\r\n\r\n", rfc822Date);
		peer().send(header, header.GetLength(), MSG_NOSIGNAL);

		time_t startTime = time(NULL);

		sessionId = EventStreamingSingleton::instance()->GetNewSessionId() + " -";
		logMsg.Format("%s Event streaming start", sessionId);
		LOG4CXX_INFO(s_log, logMsg);

		EventStreamingSessionRef session(new EventStreamingSession());
		EventStreamingSingleton::instance()->AddSession(session);

		int sendRes = 0;
		while(sendRes >= 0)
		{
			session->WaitForMessages();

			while(session->GetNumMessages() && sendRes >= 0)
			{
				MessageRef message;

				session->GetTapeMessage(message);
				if(message.get())
				{
					CStdString msgAsSingleLineString;
					msgAsSingleLineString = message->SerializeUrl() + "\r\n";

					sendRes = peer().send(msgAsSingleLineString, msgAsSingleLineString.GetLength(), MSG_NOSIGNAL);
					if(sendRes >= 0)
					{
						messagesSent += 1;
					}
				}
			}
		}

		EventStreamingSingleton::instance()->RemoveSession(session);
		logMsg.Format("%s Stream client stop - sent %d messages in %d sec", sessionId, messagesSent, (time(NULL) - startTime));
		LOG4CXX_INFO(s_log, logMsg);
	}
	catch (CStdString& e)
	{
		CStdString error("HTTP/1.0 404 not found\r\nContent-type: text/html\r\n\r\nError\r\n");
		error = error + e + "\r\n";
		LOG4CXX_ERROR(s_log, e);
		peer().send(error, error.GetLength(), MSG_NOSIGNAL);
	}

	return 0;
}
Пример #20
0
int HttpServer::svc(void)
{
	char buf[2048];
	buf[2047] = '\0';	// security
	ACE_Time_Value timeout;
	timeout.sec(5);

	ssize_t size = peer().recv(buf, 2040, &timeout);

	if (size > 5)
	{
		try
		{
			int startUrlOffset = 5;		// get rid of "GET /" from Http request, so skip 5 chars
			char* stopUrl = ACE_OS::strstr(buf+startUrlOffset, " HTTP");	// detect location of post-URL trailing stuff
			if(!stopUrl)
			{
				throw (CStdString("Malformed http request"));							;
			}
			*stopUrl = '\0';									// Remove post-URL trailing stuff
			CStdString url(buf+startUrlOffset);
			int queryOffset = url.Find("?");
			if (queryOffset	 > 0)
			{
				// Strip beginning of URL in case the command is received as an URL "query" of the form:
				// http://hostname/service/command?type=ping
				url = url.Right(url.size() - queryOffset - 1);
			}


			CStdString className = UrlSerializer::FindClass(url);
			ObjectRef objRef = ObjectFactory::GetSingleton()->NewInstance(className);
			if (objRef.get())
			{
				objRef->DeSerializeUrl(url);
				ObjectRef response = objRef->Process();

				if(response.get() == NULL)
				{
					throw (CStdString("Command does not return a response:") + className);
				}
				else
				{
					DOMImplementation* impl =  DOMImplementationRegistry::getDOMImplementation(XStr("Core").unicodeForm());
					XERCES_CPP_NAMESPACE::DOMDocument* myDoc;
					   myDoc = impl->createDocument(
								   0,			 // root element namespace URI.
								   XStr("response").unicodeForm(),	   // root element name
								   0);			 // document type object (DTD).
					response->SerializeDom(myDoc);
					CStdString pingResponse = DomSerializer::DomNodeToString(myDoc);

					CStdString httpOk("HTTP/1.0 200 OK\r\nContent-type: text/xml\r\n\r\n");
					peer().send(httpOk, httpOk.GetLength(), MSG_NOSIGNAL);
					peer().send(pingResponse, pingResponse.GetLength(), MSG_NOSIGNAL);

					myDoc->release();
				}
			}
			else
			{
				throw (CStdString("Command not found:") + className);							;
			}

		}
		catch (CStdString &e)
		{
			CStdString error("HTTP/1.0 404 not found\r\nContent-type: text/html\r\n\r\nError\r\n");
			error = error + e + "\r\n";
			peer().send(error, error.GetLength(), MSG_NOSIGNAL);
		}
		catch(const XMLException& e)
		{
			CStdString error("HTTP/1.0 404 not found\r\nContent-type: text/html\r\n\r\nXML Error\r\n");
			peer().send(error, error.GetLength(), MSG_NOSIGNAL);
		}
	}
	else
	{
		CStdString notFound("HTTP/1.0 404 not found\r\nContent-type: text/html\r\n\r\nNot found\r\n");
		peer().send(notFound, notFound.GetLength(), MSG_NOSIGNAL);
	}
	return 0;
}
Пример #21
0
void Connection::respond(ev::io &w) {
    if (requestType < 0) {
        badRequest(w);
        return;
    }
    switch (requestType) {
        case GET:
                {
                    std::string filename = rootDir;
                    filename.append(filePath);
                    int fd = open(filename.c_str(), O_RDONLY);
                    if (fd == -1) {
                        switch (errno) {
                            case EACCES: {
                                             forbidden(w);
                                             break;
                                         }
                            default:
                                         {
                                             notFound(w);
                                             break;
                                         }
                        }
                        return;
                    }
                    struct stat stat_buf;
                    if (-1 == fstat(fd, &stat_buf)) {
                        close(fd);
                        internalError(w);
                    }
                    if (S_ISDIR(stat_buf.st_mode)) {
                        forbidden(w);
                        close(fd);
                        return;
                    }

                    std::ostringstream response;
                    response << "HTTP/1.0 200 OK\r\nContent-Length: ";
                    response << stat_buf.st_size << "\r\n";

                    char *point;
                    const char *contentType = "application/octet-stream";
                    if (NULL != (point = strrchr((char *)filePath.c_str(), '.'))) {
                        if (strcasecmp(point, ".gif") == 0) {
                            contentType = "image/gif";
                        } else if (strcasecmp(point, ".jpg") == 0 ||
                                   strcasecmp(point, ".jpeg") == 0) {
                            contentType = "image/jpeg";
                        } else if (strcasecmp(point, ".txt") == 0) {
                            contentType = "text/plain";
                        } else if (strcasecmp(point, ".html") == 0 ||
                                strcasecmp(point, ".htm") == 0) {
                            contentType = "text/html";
                        }
                    }
                    response << "Content-Type: " << contentType << "\r\n\r\n";

                    std::string headers = response.str();
                    send(w.fd, headers.c_str(), headers.size(), MSG_NOSIGNAL);

                    sendfile(w.fd, fd, NULL, stat_buf.st_size);
                    close(fd);
                    break;
                }
    }
    closeConnection = true;
}
Пример #22
0
/**
 * Parses a navPoly / waypoint section 
 *
 * @param pSection  the DataSection to parse.
 * @param pChunk  if not NULL this flags that we are parsing a navPoly not a
 * waypoint section as well as providing the chunk from which to get the 
 * transform information to go from local -> global coords.
 */
void ChunkView::parseNavPoly( DataSectionPtr pSection, int set, Chunk * pChunk )
{
	DataSection::iterator it;
	PolygonDef polyDef;
	int id;
	float height;

	id = pSection->asInt();
	height = pSection->readFloat("height");
	polyDef.minHeight = pSection->readFloat("minHeight",height);
	polyDef.maxHeight = pSection->readFloat("maxHeight",height);
	polyDef.set = set;

	// If chunk provided, we want to convert heights from local -> global coords.
	if (pChunk)
	{
		Vector3 vMin( pChunk->centre().x, polyDef.minHeight, pChunk->centre().z );
		Vector3 vMax( pChunk->centre().x, polyDef.maxHeight, pChunk->centre().z );

		Vector3 vMinT = pChunk->transform().applyPoint( vMin );
		Vector3 vMaxT = pChunk->transform().applyPoint( vMax );

		polyDef.minHeight = vMinT.y;
		polyDef.maxHeight = vMaxT.y;
	}

	// If there is a gap in IDs, add blank polys to fill it up.
	while (nextID_ <= id)
	{
		PolygonDef blankPoly;
		blankPoly.minHeight = 0.0f;
		blankPoly.maxHeight = 0.0f;
		blankPoly.set = 0;
		polygons_.push_back(blankPoly);
		nextID_++;
	}

	// Read all this navPoly's vertices
	for(it = pSection->begin(); it != pSection->end(); it++)
	{
		if((*it)->sectionName() == "vertex")
		{
			DataSectionPtr pVertex = *it;
			VertexDef vertexDef;
			Vector3 vinfo = pVertex->asVector3();
			vertexDef.position.x = vinfo.x;
			vertexDef.position.y = vinfo.y;
			vertexDef.adjacentID = int( vinfo.z );

			// if pChunk provided, want to convert vertex to golbal coords.
			if (pChunk)
			{
				Vector3 v( vinfo.x, polyDef.maxHeight, vinfo.y );
				Vector3 vT = pChunk->transform().applyPoint( v );

				vertexDef.position.x = vT.x;
				vertexDef.position.y = vT.z;
			}

			std::string notFound( "__NOT_FOUND__" );
			std::string adjacentChunk = pVertex->readString("adjacentChunk",notFound);
			// if there is an adjacentChunk tag
			// note: only ever occurs within legacy waypoint tags.
			if ( adjacentChunk != notFound ) 
			{
				if (vertexDef.adjacentID != 0) 
				{
					WARNING_MSG( "ChunkView::parseNavPoly: adjacentChunk tag"
						" found but edge adjacency not 0.\n" );
				}
				vertexDef.adjacentID = CHUNK_ADJACENT_CONSTANT;
			}

			// if adjacent to another chunk, flag this in vertexDef.
			// also make (navPoly) adjacentID more sensible.
			vertexDef.adjToAnotherChunk = false;
			if (vertexDef.adjacentID == CHUNK_ADJACENT_CONSTANT) 
			{
				vertexDef.adjacentID = 0;
				vertexDef.adjToAnotherChunk = true;
			}

			polyDef.vertices.push_back( vertexDef );

			if(!minMaxValid_)
			{
				gridMin_.x = vertexDef.position.x;
				gridMin_.z = vertexDef.position.y;
				gridMin_.y = -1000.0f;
				gridMax_.x = vertexDef.position.x;
				gridMax_.z = vertexDef.position.y;
				gridMax_.y = 1000.0f;
				minMaxValid_ = true;
			}
			else
			{
				if(vertexDef.position.x < gridMin_.x)
					gridMin_.x = vertexDef.position.x;
				if(vertexDef.position.y < gridMin_.z)
					gridMin_.z = vertexDef.position.y;
				if(vertexDef.position.x > gridMax_.x)
					gridMax_.x = vertexDef.position.x;
				if(vertexDef.position.y > gridMax_.z)
					gridMax_.z = vertexDef.position.y;
			}
		}
	}

	polygons_[id-1] = polyDef;
}
Пример #23
0
void *MSHashTable::lookup(unsigned long key_) const
{
  MSHashEntry *entry=searchBucketFor(bucket(hash(key_)),key_);
  if (entry==0) return (void *)notFound();
  else return entry->value();
}