void ArchiveEditable::commitIndex(int index_size)
	{
#define _SWAP_(n)	(((n)&0xFF000000)>>24|((n)&0xFF0000)>>8|((n)&0xFF00)<<8|((n)&0xFF)<<24)
		index_size_ = index_size;
		if(filter_) filter_->close();
		rdbuf(filebuf());
		File::seekp(0);
		if(crypt_state_ == CRYPT && filter_) {
			flags_ |= FLAG_CRYPTED;
		}
		else {
			flags_ = 0;
		}
		(*this) << (int)_SWAP_('GCAR') << index_size_ << flags_;
		if(crypt_state_ == CRYPT && filter_) {
			*iv_ = index_iv_;
			filter_->open(rdbuf(filter_));
		}
		for(ListItr i = list_.begin(); i != list_.end(); i++) {
			if(i->attr != EntryAttr::REMOVE) {
				(*this) << i->id.c_str() << i->time << i->size << i->pos;
				PRNN("write "<<(*i));
			}
		}
		File::clear();
#undef _SWAP_
	}
Example #2
0
void BaseEntityParser::parseReference()
{
	// We may need to go back if things go wrong...
	filebuf previous_start(text);
	try {
		consumeToken("&");
		checkForEOF(); // There should be more characters to read

		if ( *text == '#' ) {
			parseCharacterReference();
		} else if ( is_in(*text, LETTERS) ) {
			parseEntityReference();
		} else {
			// WTF? What is this thing?
			throw InvalidCharError("Unexpected character while "
					       "parsing reference.");
		}

		// Consume trailing ';' if it is there...
		if ( not text.eof() and *text == ';') {
			consumeToken(';');
		}

	// Why Oh! Why doesn't C++ has multiple catch blocks...
	} catch (InvalidCharError&) {
		// Invalid or unexpected character found?
		// Just turn everything we had from previous_start to
		// the current read position into text content.
		int length = this->text.current - previous_start.current;
		handlePureText(filebuf(previous_start.current, length ));
	} catch (UnknownEntityReferenceError&) {
		// Unknown entity?
		// Just turn everything we had from previous_start to
		// the current read position into text content.
		int length = this->text.current - previous_start.current;
		handlePureText(filebuf(previous_start.current, length ));
	} catch (ParserEOFError&) {
		// Unexpected EOF?
		// Just turn everything we had from previous_start to
		// to this->text's end into text content.
		handlePureText(previous_start);
	}
}
Example #3
0
static bbFile *open( BBStr *f,int n ){
	string t=*f;
	filebuf *buf=d_new filebuf();
	if( buf->open( t.c_str(),(std::ios_base::openmode)n|ios_base::binary ) ){
		bbFile *f=d_new bbFile( buf );
		file_set.insert( f );
		return f;
	}
	delete buf;
	return 0;
}
Example #4
0
std::string Task::GetCpuSetPath() const {
  if (auto file = OpenTaskFilePointer("cpuset")) {
    stdio_filebuf<char> filebuf(file.get());
    std::istream file_stream(&filebuf);

    std::string line = "";
    std::getline(file_stream, line);

    return Trim(line);
  } else {
    return "";
  }
}
Example #5
0
void BaseHTMLParser::readText()
{
	const char* start = text.current;
	int length = 0;

	while ( not text.eof() and (*text != '<' or not this->tagFollows()) ){
		++text;
		++length;
	}
	// We may have reached the end or found a possible tag start
	// in any case text[start:i] has all that matter for us -- nothing
	// more, nothing less.
	this->handleText( filebuf(start,length) );

	// Parsing should re-start at current position - OK
}
Example #6
0
filebuf IconvWrapper::convert(const filebuf& input)
{
	size_t ret = 0;

	char* BUFFER;
	size_t BUFFSIZE;

	size_t inbytesleft = 0;
	size_t outbytesleft = 0;
	char* input_ptr = 0;
	char* output_ptr = 0;

	char* output = 0; // The final result will go here...
	size_t output_size = 0;

	// How much data should be put avaiable to iconv?
	// How about twice as much as input's length?
	inbytesleft = input.len();
	BUFFSIZE = 2 * inbytesleft;
	outbytesleft = BUFFSIZE;

	// Get memory to hold our converted data.
	BUFFER = new char[ BUFFSIZE ];

	input_ptr = (char*)input.current;
	output_ptr = BUFFER;

	ret = iconv(	cd,
			&input_ptr, &inbytesleft, 
			&output_ptr, &outbytesleft);
	if (ret == size_t(-1)) {
		delete[] BUFFER;
		throw IconvError("While converting...");
	} 

	// Got here? So everything went fine.

	// Copy data to a more memory-efficient location
	output_size = BUFFSIZE - outbytesleft;
	output = new char[output_size];
	memcpy(output, BUFFER, output_size);
	delete[] BUFFER;

	return filebuf(output, output_size);
}
Example #7
0
filebuf BaseHTMLParser::readAttValue()
{
	/* [25] Eq        ::= S? '=' S?
	 * [10] AttValue  ::= '"' ([^<&"] | Reference)* '"'
	 *		             |  "'" ([^<&'] | Reference)* "'"
	 */

	filebuf previous_start(this->text); // Just in case we need to go back
	filebuf value;
	char token;

	this->readSpace();
	if (*text != '=') {
		// plain HTML attribute with no value
		text.current = previous_start.current; // Get back
		value = filebuf(); //value = None
	} else {

		this->consumeToken('='); // Get past the '='
		this->readSpace();

		switch (*text) {
		case '\'':
			token = '\'';
			this->consumeToken(token);  // Get past the starting '
			value =  this->readUntilDelimiter(token);
			this->consumeToken(token);    // Get past the ending '
			break;
		case '"':
			token = '"';
			this->consumeToken(token);    // Get past the starting "
			value =  this->readUntilDelimiter(token);
			this->consumeToken(token);    // Get past the ending "
			break;
		default:
			// Old HTML-style attribute
			value =  this->readUntilDelimiter(WHITESPACE + ">");
		}
	}
	return value;
}
Example #8
0
void Task::ReadStatusFields() {
  if (auto file = OpenTaskFilePointer("status")) {
    stdio_filebuf<char> filebuf(file.get());
    std::istream file_stream(&filebuf);

    for (std::string line; std::getline(file_stream, line);) {
      auto offset = line.find(":");
      if (offset == std::string::npos) {
        ALOGW("ReadStatusFields: Failed to find delimiter \":\" in line=\"%s\"",
              line.c_str());
        continue;
      }

      std::string key = line.substr(0, offset);
      std::string value = Trim(line.substr(offset + 1));

      ALOGD_IF(TRACE, "Task::ReadStatusFields: key=\"%s\" value=\"%s\"",
               key.c_str(), value.c_str());

      if (key == "Name")
        name_ = value;
      else if (key == "Tgid")
        thread_group_id_ = std::strtol(value.c_str(), nullptr, 10);
      else if (key == "PPid")
        parent_process_id_ = std::strtol(value.c_str(), nullptr, 10);
      else if (key == "Uid")
        ParseUidStatusField(value, user_id_);
      else if (key == "Gid")
        ParseUidStatusField(value, group_id_);
      else if (key == "Threads")
        thread_count_ = std::strtoul(value.c_str(), nullptr, 10);
      else if (key == "Cpus_allowed")
        cpus_allowed_mask_ = std::strtoul(value.c_str(), nullptr, 16);
      else if (key == "Cpus_allowed_list")
        cpus_allowed_list_ = value;
    }
  }
}
Example #9
0
/*
 * Find printable strings of 4 or more characters
 * Always scans entire file (-a option of gnu strings)
 */
void strings(FILE *pf) {
  static char printme[1024];
  int sz;
  unsigned char *cdata;
  int nread;
  int printmeindex;
  cdata = filebuf(pf,&sz);
  nread = fread(cdata, 1, sz, pf);
  printmeindex = 0;
  if (nread > 0) {
    int i;
    unsigned char c;
    int isprintable;
    int iseol;
    for (i = 0; i < nread; i++) {
      c = cdata[i];
      isprintable = isprint(c);
      iseol = 0;
      if (c == 0 || c == '\n' || printmeindex >= sizeof(printme)-1) iseol = 1;
      if (iseol || !isprintable) {
	if (printmeindex > 3 && iseol) {
	  printme[printmeindex++] = 0;
	  printf("%s\n", printme);
	  printmeindex = 0;
	}
      }
      else if (isprintable) {
	printme[printmeindex++] = c;
      }
    }
  }
  if (printmeindex > 3) {
    printme[printmeindex++] = 0;
    printf("%s\n", printme);
    printmeindex = 0;
  }
  free(cdata);
}
Example #10
0
std::string Task::GetStatusField(const std::string& field) const {
  if (auto file = OpenTaskFilePointer("status")) {
    stdio_filebuf<char> filebuf(file.get());
    std::istream file_stream(&filebuf);

    for (std::string line; std::getline(file_stream, line);) {
      auto offset = line.find(field);

      ALOGD_IF(TRACE,
               "Task::GetStatusField: field=\"%s\" line=\"%s\" offset=%zd",
               field.c_str(), line.c_str(), offset);

      if (offset == std::string::npos)
        continue;

      // The status file has lines with the format <field>:<value>. Extract the
      // value after the colon.
      return Trim(line.substr(offset + field.size() + 1));
    }
  }

  return "[unknown]";
}
Example #11
0
	/**Default constructor.
	 *
	 * Use to build end() sentinels.
	 */
	HTMLContentWideCharStreamIterator()
	: content(filebuf()), text(), text_pos(0), put_sep(false)
	{}
Example #12
0
bool CAssetUploadQueue::AddAsset(int nAssetID)
{
	// We need a user
	CUser *pUser;
	if((pUser = m_InputContext.GetCurrentUser()) == NULL)
	{
		if(!AddInside("ASSET-UPLOADER", "<UPLOAD-RESULT><ERROR TYPE=1>User not logged in</ERROR></UPLOAD-RESULT>"))
		{
			TDVASSERT(false, "CAssetUploadQueue::AddAsset() AddInside failed");
			return false;
		}

		return true;
	}

	// Get mime type and length
	int iLength;
	CTDVString sMime;
	if (!m_InputContext.GetNamedSectionMetadata("file", iLength, sMime))
	{
		if(!AddInside("ASSET-UPLOADER", "<UPLOAD-RESULT><ERROR TYPE=2>file not found</ERROR></UPLOAD-RESULT>"))
		{
			TDVASSERT(false, "CAssetUploadQueue::AddAsset() AddInside failed");
			return false;
		}

		return true;
	}

	// Check if mime type is supported
	// This part should be extented as we add support
	// for more file formats
	if(!sMime.CompareText("image/jpeg") 
		&& !sMime.CompareText("image/gif"))
	{
		CTDVString sErr;
		sErr << "<UPLOAD-RESULT><ERROR TYPE=3>File format not supported (" << sMime << ")</ERROR></UPLOAD-RESULT>";
		if(!AddInside("ASSET-UPLOADER", sErr))
		{
			TDVASSERT(false, "CAssetUploadQueue::AddAsset() AddInside failed");
			return false;
		}

		return true;
	}

	// Make sure file is not too big.
	// 5megs = 5242880 bytes (http://www.google.co.uk/search?hl=en&q=bytes+in+5+megabytes)
	if(iLength > 5242880)
	{
		CTDVString sErr;
		sErr << "<UPLOAD-RESULT><ERROR TYPE=4>File too big (" << iLength << ")</ERROR></UPLOAD-RESULT>";
		if(!AddInside("ASSET-UPLOADER", sErr))
		{
			TDVASSERT(false, "CAssetUploadQueue::AddAsset() AddInside failed");
			return false;
		}

		return true;
	}

	// Copy file to folder //

	// Make sure folder exists (c:\\assetuploadqueue for time being) 
	const char * sQueueFolder = "c:\\assetuploadqueue";

	DWORD dwLastError;
	if(!CreateDirectory(sQueueFolder, NULL)
		&& (dwLastError = GetLastError()) != ERROR_ALREADY_EXISTS)
	{
		CTDVString sErr;
		sErr << "<UPLOAD-RESULT><ERROR TYPE=5>Failed to create folder (" << (long)dwLastError << ")</ERROR></UPLOAD-RESULT>";
		if(!AddInside("ASSET-UPLOADER", sErr))
		{
			TDVASSERT(false, "CAssetUploadQueue::AddAsset() AddInside failed");
			return false;
		}

		return true;
	}

	// Copy data into buffer
	std::vector<char> filebuf(iLength);
	if(!m_InputContext.GetParamFile("file", filebuf.size(), &filebuf[0], iLength, sMime))
	{
		if(!AddInside("ASSET-UPLOADER", "<UPLOAD-RESULT><ERROR TYPE=5>Failed to get file data</ERROR></UPLOAD-RESULT>"))
		{
			TDVASSERT(false, "CAssetUploadQueue::AddAsset() AddInside failed");
			return false;
		}

		return true;
	}

	// Dump to disk
	CTDVString sFilename;
	sFilename << sQueueFolder << "\\" << nAssetID;
	HANDLE hFile = CreateFile(sFilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if(hFile == INVALID_HANDLE_VALUE)
	{
		CTDVString sErr;
		sErr << "<UPLOAD-RESULT><ERROR TYPE=5>Failed to create file (" << (long)GetLastError() << ")</ERROR></UPLOAD-RESULT>";
		if(!AddInside("ASSET-UPLOADER", sErr))
		{
			TDVASSERT(false, "CAssetUploadQueue::AddAsset() AddInside failed");
			return false;
		}

		return true;
	}
    
	DWORD dwNumberOfBytesWritten;
	if(!WriteFile(hFile, &filebuf[0], filebuf.size(), &dwNumberOfBytesWritten, NULL))
	{
		DWORD dwError = GetLastError();
		
		CloseHandle(hFile);
		
		CTDVString sErr;
		sErr << "<UPLOAD-RESULT><ERROR TYPE=5>Failed to write to file (" << (long)dwError << ")</ERROR></UPLOAD-RESULT>";

		if(!AddInside("ASSET-UPLOADER", sErr))
		{
			TDVASSERT(false, "CAssetUploadQueue::AddAsset() AddInside failed");
			return false;
		}

		return true;
	}

	CloseHandle(hFile);

	// Add record to table
	CStoredProcedure SP;
	if(!m_InputContext.InitialiseStoredProcedureObject(&SP))
	{
		TDVASSERT(false, "CAssetUploadQueue::AddAsset() m_InputContext.InitialiseStoredProcedureObject failed");
		return false;
	}

	CTDVString sServer;
	m_InputContext.GetServerName(&sServer);

	if(!SP.MediaAssetUploadQueueAdd(nAssetID, sServer))
	{
		TDVASSERT(false, "CAssetUploadQueue::AddAsset() SP.MediaAssetUploadQueueAdd failed");
		return false;
	}

	// Report succcess
	CTDVString sMsg;
	if(!AddInside("ASSET-UPLOADER", "<UPLOAD-RESULT/>"))
	{
		TDVASSERT(false, "CAssetUploadQueue::AddAsset() AddInside failed");
		return false;
	}

	return true;
}
/***
*fstream::fstream(filedesc fd, char * sbuf, int len) - fstream constructor
*
*Purpose:
*       Constructor for fstream objects.  Creates an associated filebuf object
*       and attaches it to the given file descriptor.  Filebuf object uses
*       user-supplied buffer or is unbuffered if sbuf or len = 0.
*
*Entry:
*       fd   = file descriptor of file previously opened using _open or _sopen.
*       sbuf = pointer to character buffer or NULL if request for unbuffered.
*       len  = lenght of character buffer sbuf or 0 if request for unbuffered.
*
*Exit:
*       None.
*
*Exceptions:
*
*******************************************************************************/
        fstream::fstream(filedesc _fd, char * sbuf, int len)
: iostream(_new_crt filebuf(_fd, sbuf, len))
{
    istream::delbuf(1);
    ostream::delbuf(1);
}
Example #14
0
*	Copyright (c) 1991-1995, Microsoft Corporation.  All rights reserved.
*
*Purpose:
*	Definitions and initialization of predefined stream cerr.
*
*Revision History:
*       11 18-91  KRS   Created.
*       01-12-95  CFW   Debug CRT allocs.
*       09-10-94  CFW   Static Win32s objects do not alloc on instantiation.
*       06-14-95  CFW   Comment cleanup.
*
*******************************************************************************/
#include <cruntime.h>
#include <internal.h>
#include <iostream.h>
#include <fstream.h>
#include <dbgint.h>
#pragma hdrstop

// put contructors in special MS-specific XIFM segment
#pragma warning(disable:4074)	// ignore init_seg warning
#pragma init_seg(compiler)

#if (defined(DLL_FOR_WIN32S))
ostream_withassign cerr;
#else
ostream_withassign cerr(_new_crt filebuf(2));
#endif

static Iostream_init  __InitCerr(cerr,1);
/***
*fstream::fstream(filedesc fd) - fstream constructor
*
*Purpose:
*       Constructor for fstream objects.  Creates an associated filebuf object
*       and attaches it to the given file descriptor.
*
*Entry:
*       fd = file descriptor of file previously opened using _open or _sopen.
*
*Exit:
*       None.
*
*Exceptions:
*
*******************************************************************************/
        fstream::fstream(filedesc _fd)
: iostream(_new_crt filebuf(_fd))
{
    istream::delbuf(1);
    ostream::delbuf(1);
}
Example #16
0
*******************************************************************************/
#include <cruntime.h>
#include <internal.h>
#include <iostream.h>
#include <fstream.h>
#include <dbgint.h>
#pragma hdrstop

// put contructors in special MS-specific XIFM segment
#pragma warning(disable:4074)	// disable init_seg warning
#pragma init_seg(compiler)

#if (defined(DLL_FOR_WIN32S))
ostream_withassign cout;
#else
ostream_withassign cout(_new_crt filebuf(1));
#endif

static Iostream_init  __InitCout(cout,-1);


/***
*Iostream_init::Iostream_init() - initialize predefined streams
*
*Purpose:
*	 For compatibility only.  Not used.
*Entry:
*
*Exit:
*
*Exceptions:
Example #17
0
void BaseHTMLParser::readTagLike()
{
	filebuf previous_start (this->text);

	// Is this really  a tag-like content?
	if (not this->tagFollows()) {
		// not a tag, actually, just text... 
		// just eat the ">" as text...
		this->handleText( filebuf(this->text.current, 1));
		++text;
		return;
	}

	// Bellow here things start to get weird. We should do as a normal
	// grammar-based parser would...
	// _tagFollows garantees this is a valid reading position
	filebuf next(text);
	++next; // OK, now we are in the next char...

	try{
		if ( isalpha(*next) ) {
			// Start-Tag, section 3.1
			this->readStartTag();
		} else switch(*next) {
		case '/':
			// End-Tag, section 3.1
			this->readEndTag();
			break;
		case '?':
			// Processing Instruction, section 2.6
			this->readProcessingInstructions();
			break;
		case '!':
			// let's hope is a Comment
			//const std::string COMMENT_START = "<!--";
			if ( (text.len() > COMMENT_START_LEN)  && 
			     (std::string(text.current,COMMENT_START_LEN)
			     	== COMMENT_START) ) 
			{
				this->readComment();
			}else{
				// FIXME
				this->readGenericTagConstruction();
			}
			break;
		default:
			this->readGenericTagConstruction();
		}
	} catch (ParserEOFError) {
		// EOF found before we could finish parsing this tag-like
		// content?
		// Just turn everything we had from previous_start to _end into
		// text content.
		this->handleText( previous_start);
	} catch (InvalidCharError) {
		// InvalidCharError found?
		// Go past the offending character
		++text;
		// Just turn everything we had from previous_start to
		// the current position into text content.
		int length = this->text.current - previous_start.current;
		this->handleText( filebuf(previous_start.current,length) );
	}
}
	long ArchiveEditable::commitEntrys(int index_size)
	{
		// インデックス部のサイズ変化はここでコミット
		// 以降、ALREADYフラグの立っているエントリーはpos_を付け替えるだけで、そのままで良いはず。
//		int diff_index_real_size = align(indexalign(index_size_)) - align(indexalign(index_size));
//		if(diff_index_real_size > 0) File::remove(0, diff_index_real_size);
//		if(diff_index_real_size < 0) File::insert(0, -diff_index_real_size);
		int ret = align(index_size);
		if(crypt_state_ == CRYPT && filter_) {
			// 暗号化の場合オフセットが特殊
			ret = align(align(index_size-sizeof(int)*3)+sizeof(int)*3);
		}
		for(ListItr i = list_.begin(); i != list_.end(); i++) {
			switch(i->attr) {
			case EntryAttr::REMOVE:
				cout<<"REMOVE "<<CStr(i->id.c_str())<<endl;
				break;
			case EntryAttr::UPDATE:
				cout<<"UPDATE "<<CStr(i->id.c_str())<<endl;
				break;
			case EntryAttr::ALREADY:
				cout<<"ALREADY "<<CStr(i->id.c_str())<<endl;
				break;
			case EntryAttr::NEW:
				cout<<"NEW "<<CStr(i->id.c_str())<<endl;
				break;
			}
			switch(i->attr) {
			case EntryAttr::REMOVE:
				//i->pos = ret;
				//File::remove(i->pos, align(i->size));
				break;
			case EntryAttr::UPDATE:
				/*cout<<"UPDATE "<<CStr(i->name.c_str())<<endl;
				{
					int diff_size = align(index_[i->name].size) - align(i->size);
					i->pos = ret;
					ret += align(i->size);
					if(diff_size > 0) File::remove(i->pos,  diff_size);
					if(diff_size < 0) File::insert(i->pos, -diff_size);
					File::seek(i->pos);
					{
						File file(i->name.c_str());
						file.extract(*this, 0, file.length());
					}
					int align_size = align(i->size);
					for(int j = 0; j < align_size - i->size; j++) (*this) << '\0';
				}
				break;*/
			case EntryAttr::ALREADY:
			case EntryAttr::NEW:
				{
					i->pos = ret;
					ret += align(i->size);
					preseek(*i);
					File::seekp(i->pos);
					if(crypt_state_ == CRYPT && filter_) {
						filter_->open(rdbuf(filter_));
					}
					if(i->strm) (*this) << i->strm->rdbuf();
					else {
						File file(i->id.c_str());
						//(*this) << file.rdbuf();
						file.extract(*this, 0, file.length());
					}
					int align_size = align(i->size);
					for(int j = 0; j < align_size - i->size; j++) (*this) << '\0';
					sync();
					rdbuf(filebuf());
				}
				break;
			default:
				i->pos = ret;
				ret += align(i->size);
			}
		}
		File::clear();
		assert(ret > 0);
		return ret;
	}
Example #19
0
	/**Default constructor.
	 *
	 * Use do build end() sentinels
	 */
	HTMLContentIterator(): content(filebuf()) {}