Esempio n. 1
0
size_t
AbyssServer::Session::Impl::contentLength() const {

    try {
        const char * const contentLength = 
            RequestHeaderValue(this->cSessionP, "content-length");
        
        if (contentLength == NULL)
            throwf("Header is not present");
        else {
            if (contentLength[0] == '\0')
                throwf("The value is a null string");
            else {
                unsigned long contentLengthValue;
                char * tail;
        
                contentLengthValue = strtoul(contentLength, &tail, 10);
        
                if (*tail != '\0')
                    throwf("There's non-numeric crap in the value: '%s'",
                           tail);
                else if ((unsigned long)(size_t)contentLengthValue 
                         != contentLengthValue)
                    throwf("Value is too large; "
                           "we can't even do arithmetic on it: '%s'",
                           contentLength);
                else
                    return (size_t)contentLengthValue;
            }
        }
    } catch (exception const& e) {
        throw AbyssServer::Exception(
            400, string("Invalid content-length header field.  ") + e.what());
    }
}
Esempio n. 2
0
void SAppBase::loadConfig(const std::string& name, bool saveOnExit)
{
	Configs::iterator i = m_configs.find(name);
	if (i != m_configs.end())
		throwf("Config with name '" + name + "' has already been loaded.");

	SavedConfigs::iterator j = m_savedConfigs.find(name);
	if (j != m_savedConfigs.end())
		throwf("Config with name '" + name + "' has already been loaded.");

	Config* config = new Config();
	
	Path configPath = pathConfig(name);
	Path configLocalPath = pathLocalSettings() + name;

	if (saveOnExit || configLocalPath.exists())
		config->add(*new ConfigService(configLocalPath, !saveOnExit));

	config->add(*new ConfigService(configPath, true));

	if (!saveOnExit)
		m_configs[name] = config;
	else
		m_savedConfigs[name] = std::pair<Config*, Path>(config, configLocalPath);
	
	config->load();
}
Esempio n. 3
0
jint handleErrors(JNIEnv* env, z_stream* stream, jint inLength, int outLength, jint* communicationArray, int code) {
    int consumed = inLength - stream->avail_in;
    int written = outLength - stream->avail_out;

    communicationArray[0] = consumed;
    communicationArray[1] = written;

    if (code == Z_OK) {
        return 0;
    } else if (code == Z_STREAM_END) {
        return 1;
    } else {
        char* msg = stream->msg == NULL ? "unknown" : stream->msg;
        switch (code) {
            case Z_STREAM_END:
                return 1;
            case Z_DATA_ERROR:
                throwf(env, INVALID_DATA_EXCEPTION, "Invalid input data: %s)", msg);
                break;
            case Z_BUF_ERROR:
                throw(env, ILLEGAL_STATE_EXCEPTION, "Buffer is empty/no progress possible");
                break;
            case Z_STREAM_ERROR:
                throwf(env, ILLEGAL_STATE_EXCEPTION, "Internal error! Stream in invalid state: %s", msg);
                break;
            case Z_MEM_ERROR:
                throw(env, OUT_OF_MEMORY_ERROR, "Zlib ran out of memory");
                break;
            default:
                throwf(env, RUNTIME_EXCEPTION, "Unknown error code %d: %s", code, msg);
                break;
        }
        return -1;
    }
}
static void
writeFd(int                   const fd,
        const unsigned char * const data,
        size_t                const size,
        size_t *              const bytesWrittenP) {

    size_t totalBytesWritten;
    bool full;  // File image is "full" for now - won't take any more data

    full = false;
    totalBytesWritten = 0;

    while (totalBytesWritten < size && !full) {
        ssize_t rc;

        rc = write(fd, &data[totalBytesWritten], size - totalBytesWritten);

        if (rc < 0) {
            if (errno == EAGAIN)
                full = true;
            else
                throwf("write() of socket failed with errno %d (%s)",
                       errno, strerror(errno));
        } else if (rc == 0)
            throwf("Zero byte short write.");
        else {
            size_t const bytesWritten(rc);
            totalBytesWritten += bytesWritten;
        }
    }
    *bytesWrittenP = totalBytesWritten;
}
void
packetSocket::verifyNothingAccumulated() {
/*----------------------------------------------------------------------------
   Throw an error if there is a partial packet accumulated.
-----------------------------------------------------------------------------*/
    if (this->inEscapeSeq)
        throwf("Streams socket closed in the middle of an "
               "escape sequence");
    
    if (this->inPacket)
        throwf("Stream socket closed in the middle of a packet "
               "(%u bytes of packet received; no END marker to mark "
               "end of packet)", this->packetAccumP->getLength());
}
void
packetSocket::takeSomeEscapeSeq(const unsigned char * const buffer,
                                size_t                const length,
                                size_t *              const bytesTakenP) {
/*----------------------------------------------------------------------------
   Take and process some bytes from the incoming stream 'buffer',
   which contains 'length' bytes, assuming they are within an escape
   sequence.
-----------------------------------------------------------------------------*/
    size_t bytesTaken;

    bytesTaken = 0;

    while (this->escAccum.len < 3 && bytesTaken < length)
        this->escAccum.bytes[this->escAccum.len++] = buffer[bytesTaken++];

    assert(this->escAccum.len <= 3);

    if (this->escAccum.len == 3) {
        if (0) {
        } else if (xmlrpc_memeq(this->escAccum.bytes, "NOP", 3)) {
            // Nothing to do
        } else if (xmlrpc_memeq(this->escAccum.bytes, "PKT", 3)) {
            this->packetAccumP = packetPtr(new packet);
            this->inPacket = true;
        } else if (xmlrpc_memeq(this->escAccum.bytes, "END", 3)) {
            if (this->inPacket) {
                this->readBuffer.push(this->packetAccumP);
                this->inPacket = false;
                this->packetAccumP = packetPtr();
            } else
                throwf("END control word received without preceding PKT");
        } else if (xmlrpc_memeq(this->escAccum.bytes, "ESC", 3)) {
            if (this->inPacket)
                this->packetAccumP->addData((const unsigned char *)ESC_STR, 1);
            else
                throwf("ESC control work received outside of a packet");
        } else
            throwf("Invalid escape sequence 0x%02x%02x%02x read from "
                   "stream socket under packet socket",
                   this->escAccum.bytes[0],
                   this->escAccum.bytes[1],
                   this->escAccum.bytes[2]);
        
        this->inEscapeSeq = false;
        this->escAccum.len = 0;
    }
    *bytesTakenP = bytesTaken;
}
Esempio n. 7
0
typename File<A>::MemberState& File<A>::makeObjectFileForMember(const Entry* member) const
{
	// in case member was instantiated earlier but not needed yet
	typename MemberToStateMap::iterator pos = _instantiatedEntries.find(member);
	if ( pos != _instantiatedEntries.end() )
		return pos->second;

	const char* memberName = member->name();
	char memberPath[strlen(this->path()) + strlen(memberName)+4];
	strcpy(memberPath, this->path());
	strcat(memberPath, "(");
	strcat(memberPath, memberName);
	strcat(memberPath, ")");
	//fprintf(stderr, "using %s from %s\n", memberName, this->path());
	try {
		// range check
		if ( member > (Entry*)(_archiveFileContent+_archiveFilelength) )
			throwf("corrupt archive, member starts past end of file");										
		if ( (member->content() + member->contentSize()) > (_archiveFileContent+_archiveFilelength) )
			throwf("corrupt archive, member contents extends past end of file");										
		const char* mPath = strdup(memberPath);
		// offset the ordinals in this mach-o .o file, so that atoms layout in same order as in archive
		uint32_t memberIndex = ((uint8_t*)member - _archiveFileContent)/sizeof(ar_hdr);
		// see if member is mach-o file
		ld::relocatable::File* result = mach_o::relocatable::parse(member->content(), member->contentSize(), 
																	mPath, member->modificationTime(), 
																	this->ordinal() + memberIndex, _objOpts);
		if ( result != NULL ) {
			MemberState state = {result, false, false};
			_instantiatedEntries[member] = state;
			return _instantiatedEntries[member];
		}
		// see if member is llvm bitcode file
		result = lto::parse(member->content(), member->contentSize(), 
								mPath, member->modificationTime(), this->ordinal() + memberIndex, 
								_objOpts.architecture, _objOpts.subType, _logAllFiles);
		if ( result != NULL ) {
			MemberState state = {result, false, false};
			_instantiatedEntries[member] = state;
			return _instantiatedEntries[member];
		}
			
		throwf("archive member '%s' with length %d is not mach-o or llvm bitcode", memberName, member->contentSize());
	}
	catch (const char* msg) {
		throwf("in %s, %s", memberPath, msg);
	}
}
Esempio n. 8
0
File: cave.c Progetto: zu-gabe/Game
/*
 * Retrieve cave table information for the given cave id.
 */
void get_cave_info (db_t *database, int cave_id, struct Cave *cave)
{
  db_result_t *result = db_query(database,
	"SELECT * FROM " DB_TABLE_CAVE " WHERE caveID = %d", cave_id);

  if (!db_result_next_row(result))
    throwf(SQL_EXCEPTION, "get_cave_info: cave %d not found", cave_id);

  cave->result = result;
  cave->cave_id = cave_id;
  cave->xpos = db_result_get_int(result, "xCoord");
  cave->ypos = db_result_get_int(result, "yCoord");
  cave->name = db_result_get_string(result, "name");
  cave->player_id = db_result_get_int(result, "playerID");
  cave->terrain = db_result_get_int(result, "terrain");
  cave->takeoverable = db_result_get_int(result, "takeoverable");
  cave->artefacts = db_result_get_int(result, "artefacts");
  cave->heroID = db_result_get_int(result, "hero");
  cave->monster_id = db_result_get_int(result, "monsterID");
  cave->secure = db_result_get_int(result, "secureCave");
  cave->protect_end = db_result_get_time(result, "protection_end");
  get_resource_list(result, cave->resource);
  get_building_list(result, cave->building);
  get_science_list(result, cave->science);
  get_defense_system_list(result, cave->defense_system);
  get_unit_list(result, cave->unit);
  get_effect_list(result, cave->effect);
}
void DirectSoundLibrary::refreshDevices()
{
	DirectSoundEnumerate(enumDevice, (void*)this);

	if (_devices.empty())
		throwf("DirectSoundLibrary: No devices found.");
}
Esempio n. 10
0
int main(int argc, const char* argv[])
{
	try {
		for(int i=1; i < argc; ++i) {
			const char* arg = argv[i];
			if ( arg[0] == '-' ) {
				if ( strcmp(arg, "-no_content") == 0 ) {
					
				}
				else {
					throwf("unknown option: %s\n", arg);
				}
			}
			else {
				check(arg);
			}
		}
	}
	catch (const char* msg) {
		fprintf(stderr, "machocheck failed: %s\n", msg);
		return 1;
	}
	
	return 0;
}
Esempio n. 11
0
void
packetSocket::processBytesRead(const unsigned char * const buffer,
                               size_t                const bytesRead) {

    unsigned int cursor;  // Cursor into buffer[]
    cursor = 0;
    while (cursor < bytesRead) {
        size_t bytesTaken;

        if (this->inEscapeSeq)
            this->takeSomeEscapeSeq(&buffer[cursor],
                                    bytesRead - cursor,
                                    &bytesTaken);
        else if (buffer[cursor] == ESC) {
            this->inEscapeSeq = true;
            bytesTaken = 1;
        } else if (this->inPacket)
            this->takeSomePacket(&buffer[cursor],
                                 bytesRead - cursor,
                                 &bytesTaken);
        else
            throwf("Byte 0x%02x is not in a packet or escape sequence.  "
                   "Sender is probably not using packet socket protocol",
                   buffer[cursor]);
        
        cursor += bytesTaken;
    }
}
void MP3EncoderBladeEnc::initEncoder()
{
	BE_CONFIG config;
	memset(&config, 0, sizeof(config));
	config.dwConfig = BE_CONFIG_LAME;
	config.format.LHV1.dwStructVersion = 1;
	config.format.LHV1.dwStructSize = sizeof(config);
	config.format.LHV1.dwSampleRate = 44100;
	config.format.LHV1.nMode = BE_MP3_MODE_JSTEREO;
	config.format.LHV1.nPreset = LQP_STANDARD;
	config.format.LHV1.nVbrMethod = VBR_METHOD_DEFAULT;
	config.format.LHV1.bWriteVBRHeader = true;
	config.format.LHV1.bEnableVBR = true;

	BE_ERR err = beInitStream(&config, &m_writeSamples, &m_minOutputSize, &m_handle);
	if (err != BE_ERR_SUCCESSFUL)
		throwf("MP3EncoderBladeEnc: couldn't open stream (%s)", error(err).c_str());

	m_writeBytes = (BufferFormat::Local.bytesPerSample() * m_writeSamples);
	m_writtenBytes = 0;

	m_bufferLeft = new char[m_writeBytes / 2];
	m_bufferRight = new char[m_writeBytes / 2];
	m_bufferOutput = new char[m_minOutputSize];

	m_writeLeft = BufferFormat::Local.buf(m_bufferLeft);
	m_writeRight = BufferFormat::Local.buf(m_bufferRight);
}
Esempio n. 13
0
Path Path::exePath()
{
#if IS_OSX
//	CFBundleRef mainBundle = CFBundleGetMainBundle();
//	CFURLRef exePath = CFBundleCopyExecutableURL(mainBundle);
//
//	if (!exePath)
//		throwf("No executable found.");
//
//	UInt8 fsRep[PATH_MAX];
//	CFURLGetFileSystemRepresentation(exePath, true, fsRep, PATH_MAX);
//
//	return Path((char*)fsRep);
	return Path();
#elif IS_LINUX
	portRequired("Path::exePath");
#else
	char fsRepA[PATH_MAX] = {0};
	int result = GetModuleFileName(0, fsRepA, PATH_MAX);

	if (result == 0)
	{
		throwf("Couldn't get exe path.");
	}

	return Path(fsRepA);
#endif
}
Esempio n. 14
0
void
serverCgi_impl::establishRegistry(serverCgi::constrOpt const& opt) {

    if (!opt.present.registryP && !opt.present.registryPtr)
        throwf("You must specify the 'registryP' or 'registryPtr' option");
    else if (opt.present.registryP && opt.present.registryPtr)
        throwf("You may not specify both the 'registryP' and "
               "the 'registryPtr' options");
    else {
        if (opt.present.registryP)
            this->registryP      = opt.value.registryP;
        else {
            this->registryHolder = opt.value.registryPtr;
            this->registryP      = opt.value.registryPtr.get();
        }
    }
}
void MP3EncoderBladeEnc::consume(const void* data, int bytes)
{
	if (!m_stream.is_open())
		throwf("MP3EncoderBladeEnc: Write called, but stream is not open.");

	if (!m_stream.good())
		return;

	Critical(m_writing);

	const BufferFormat::LocalFormat::SampleElement* eData = BufferFormat::Local.buf((void*)data);

	int bytesPerSample = BufferFormat::Local.bytesPerSample();

	while (bytes > 0)
	{
		while (bytes > 0 && m_writtenBytes < m_writeBytes)
		{
			*m_writeLeft++ = *eData++ * 32767.0f;
			*m_writeRight++ = *eData++ * 32767.0f;

			m_writtenBytes += bytesPerSample;
			bytes -= bytesPerSample;
		}

		assert(bytes >= 0);

		if (m_writtenBytes == m_writeBytes)
		{
			DWORD outputSamples = m_minOutputSize;

			BE_ERR err = beEncodeChunkFloatS16NI(m_handle, m_writeSamples, (float*)m_bufferLeft, (float*)m_bufferRight, (PBYTE)m_bufferOutput, &outputSamples);
			if (err != BE_ERR_SUCCESSFUL)
				throwf("MP3EncoderBladeEnc: encode error (%s)", error(err).c_str());

			m_stream.write(m_bufferOutput, outputSamples);
			if (!m_stream.good())
				derr << "MP3EncoderBladeEnc: error writing to file " << m_path.c_str() << derr.endl;

			m_writeLeft = BufferFormat::Local.buf(m_bufferLeft);
			m_writeRight = BufferFormat::Local.buf(m_bufferRight);
			m_writtenBytes = 0;
		}
	}
}
Esempio n. 16
0
    void
    serverPstreamConn_impl::establishPacketSocket(
            serverPstreamConn::constrOpt_impl const &opt) {

        if (!opt.present.socketFd)
            throwf("You must provide a 'socketFd' constructor option.");

        auto_ptr<packetSocket> packetSocketAP;

        try {
            auto_ptr<packetSocket> p(new packetSocket(opt.value.socketFd));
            packetSocketAP = p;
        } catch (exception const &e) {
            throwf("Unable to create packet socket out of file descriptor %d.  %s",
                   opt.value.socketFd, e.what());
        }
        this->packetSocketP = packetSocketAP.get();
        packetSocketAP.release();
    }
Esempio n. 17
0
void MachOChecker<A>::checkSection(const macho_segment_command<P>* segCmd, const macho_section<P>* sect)
{
	uint8_t sectionType = (sect->flags() & SECTION_TYPE);
	if ( sectionType == S_ZEROFILL ) {
		if ( sect->offset() != 0 )
			throwf("section offset should be zero for zero-fill section %s", sect->sectname());
	}
	
	// more section tests here
}
Esempio n. 18
0
File: cave.c Progetto: zu-gabe/Game
/*
 * Retrieve the owner (player id) of the given gave.
 */
int get_cave_owner (db_t *database, int cave_id)
{
  db_result_t *result = db_query(database,
	"SELECT playerID FROM " DB_TABLE_CAVE " WHERE caveID = %d", cave_id);

  if (!db_result_next_row(result))
    throwf(SQL_EXCEPTION, "get_cave_owner: cave %d not found", cave_id);

  return db_result_get_int_at(result, 0);
}
Esempio n. 19
0
    void
    serverPstreamConn_impl::processRecdPacket(packetPtr const callPacketP,
                                              callInfo *const callInfoP) {

        packetPtr responsePacketP;
        try {
            processCall(this->registryP, callPacketP, callInfoP,
                        &responsePacketP);
        } catch (exception const &e) {
            throwf("Error executing received packet as an XML-RPC RPC.  %s",
                   e.what());
        }
        try {
            this->packetSocketP->writeWait(responsePacketP);
        } catch (exception const &e) {
            throwf("Failed to write the response to the packet socket.  %s",
                   e.what());
        }
    }
Esempio n. 20
0
static ObjectFile::Reader* createReader(const char* path, const ObjectFile::ReaderOptions& options)
{
	struct stat stat_buf;
	
	int fd = ::open(path, O_RDONLY, 0);
	if ( fd == -1 )
		throwf("cannot open file: %s", path);
	::fstat(fd, &stat_buf);
	uint8_t* p = (uint8_t*)::mmap(NULL, stat_buf.st_size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
	::close(fd);
	const mach_header* mh = (mach_header*)p;
	if ( mh->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
		const struct fat_header* fh = (struct fat_header*)p;
		const struct fat_arch* archs = (struct fat_arch*)(p + sizeof(struct fat_header));
		for (unsigned long i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
			if ( OSSwapBigToHostInt32(archs[i].cputype) == (uint32_t)sPreferredArch ) {
				if ( ((uint32_t)sPreferredSubArch == 0xFFFFFFFF) || ((uint32_t)sPreferredSubArch == OSSwapBigToHostInt32(archs[i].cpusubtype)) ) {
					p = p + OSSwapBigToHostInt32(archs[i].offset);
					mh = (struct mach_header*)p;
					break;
				}
			}
		}
	}
	if ( mach_o::relocatable::Reader<x86>::validFile(p) )
		return new mach_o::relocatable::Reader<x86>::Reader(p, path, 0, options, 0);
	else if ( mach_o::relocatable::Reader<ppc>::validFile(p) )
		return new mach_o::relocatable::Reader<ppc>::Reader(p, path, 0, options, 0);
	else if ( mach_o::relocatable::Reader<ppc64>::validFile(p) )
		return new mach_o::relocatable::Reader<ppc64>::Reader(p, path, 0, options, 0);
	else if ( mach_o::relocatable::Reader<x86_64>::validFile(p) )
		return new mach_o::relocatable::Reader<x86_64>::Reader(p, path, 0, options, 0);
	else if ( mach_o::relocatable::Reader<arm>::validFile(p) )
		return new mach_o::relocatable::Reader<arm>::Reader(p, path, 0, options, 0);
#if LTO_SUPPORT
	if ( lto::Reader::validFile(p, stat_buf.st_size, 0) ) {
		return new lto::Reader(p, stat_buf.st_size, path, 0, options, 0);
	}
#endif
	
	throwf("not a mach-o object file: %s", path);
}
DirectSoundDevice& DirectSoundLibrary::defaultDevice() const
{
	for (Devices::const_iterator i = _devices.begin(); i != _devices.end(); ++i)
	{
		if (i->second->isDefault())
			return *i->second;
	}

	throwf("DirectSoundLibrary: No primary device.");
	return *(DirectSoundDevice*)0;
}
Esempio n. 22
0
void oogame_init (void)
{
    ooduck_init ();

    if (SDL_Init (SDL_INIT_VIDEO) < 0)
    {
        throwf (SDLException, "Cannot initialize SDL: %s", SDL_GetError ());
    }

    atexit (oogame_deinit);
}
Esempio n. 23
0
void SAppBase::createFonts()
{
	// font
	if (!Font().createSystemFont("Arial", "arial", 24))
		throwf("Couldn't create SAppBase font");
	Font().set("arial");
	Font().activeFont()->setScale(0.75f);

	if (!Font().copyFont("arial", "smallarial", 0.5f))
		throwf("Couldn't create SAppBase font");

	if (!Font().copyFont("arial", "worldarial", 500.0f))
		throwf("Couldn't create SAppBase font");

	if (!Font().createSystemFont("Arial", "bigarial", 72, 512))
		throwf("Couldn't create bigarial");
	Font().get("bigarial")->setScale(2.0f);

	Font().makeTextureFonts();
}
Esempio n. 24
0
string const
AbyssServer::Session::uriQuery() const {

    const TRequestInfo * requestInfoP;

    SessionGetRequestInfo(this->implP->cSessionP, &requestInfoP);

    if (requestInfoP->query)
        return string(requestInfoP->query);
    else
        throwf("Request URI has no query part");
}
Esempio n. 25
0
string const
AbyssServer::Session::host() const {

    const TRequestInfo * requestInfoP;

    SessionGetRequestInfo(this->implP->cSessionP, &requestInfoP);

    if (requestInfoP->host)
        return string(requestInfoP->host);
    else
        throwf("Request does not specify a host");
}
Esempio n. 26
0
string const
AbyssServer::Session::useragent() const {

    const TRequestInfo * requestInfoP;

    SessionGetRequestInfo(this->implP->cSessionP, &requestInfoP);

    if (requestInfoP->from)
        return string(requestInfoP->useragent);
    else
        throwf("Request header does not have a 'useragent' field");
}
Esempio n. 27
0
string const
AbyssServer::Session::referer() const {

    const TRequestInfo * requestInfoP;

    SessionGetRequestInfo(this->implP->cSessionP, &requestInfoP);

    if (requestInfoP->referer)
        return string(requestInfoP->from);
    else
        throwf("Request header does not have a 'referer' field");
}
Esempio n. 28
0
void
packetSocket::readWait(volatile const int * const interruptP,
                       bool *               const eofP,
                       packetPtr *          const packetPP) {

    bool gotPacket;

    this->readWait(interruptP, eofP, &gotPacket, packetPP);

    if (!gotPacket)
        throwf("Packet read was interrupted");
}
Esempio n. 29
0
void
AbyssServer::Session::Impl::startWriteResponse() {

    // Note that ResponseWriteStart() assumes no response has been started; it
    // asserts that fact.

    if (this->responseStarted)
        throwf("Attempt to write multiple responses in same session");

    ResponseWriteStart(this->cSessionP);

    this->responseStarted = true;
}
Esempio n. 30
0
string const
AbyssServer::Session::user() const {

    const TRequestInfo * requestInfoP;

    SessionGetRequestInfo(this->implP->cSessionP, &requestInfoP);

    if (requestInfoP->user)
        return string(requestInfoP->user);
    else
        throwf("Request header does not identify a user or "
               "server could not authenticate the identity");
}