예제 #1
0
파일: EnvisatFile.c 프로젝트: afarnham/gdal
int EnvisatFile_ReadDatasetChunk( EnvisatFile *self, 
                                  int ds_index,
                                  int offset,
                                  int size,
                                  void * buffer )

{
    if( ds_index < 0 || ds_index >= self->ds_count )
    {
        SendError( "Attempt to read non-existant dataset in "
                   "EnvisatFile_ReadDatasetChunk()" );
        return FAILURE;
    }

    if( offset < 0 
        || offset + size > self->ds_info[ds_index]->ds_size )
    {
        SendError( "Attempt to read beyond end of dataset in "
                   "EnvisatFile_ReadDatasetChunk()" );
        return FAILURE;
    }

    if( VSIFSeekL( self->fp, self->ds_info[ds_index]->ds_offset+offset, SEEK_SET )
        != 0 )
    {
        SendError( "seek failed in EnvisatFile_ReadChunk()" );
        return FAILURE;
    }

    if( (int) VSIFReadL( buffer, 1, size, self->fp ) != size )
    {
        SendError( "read failed in EnvisatFile_ReadChunk()" );
        return FAILURE;
    }

    return SUCCESS;
}
예제 #2
0
// processes GET
void GetURL(int conn, const char *url)
{
 if (!url) return;
 printf(">>> GET %s\n", url);
 const int len = strlen(url);
 
 // sanitize url
 // TODO!
 
 // block request of hidden files
 if (len > 1) {
  if (url[1] == '.') {
   SendError(conn, 403, url);
   return;
  }
 }
 
 // point to resource
 const char *file = url;
 
 // default to index
 if (strcmp(url,"/") == 0) {
  file = "/index.html";
 }
 // TODO: generate folder index?
 
 // expand url to local filename
 static char filename[256];
 memset(filename,'@',256);
 sprintf(filename,"%s%s", g_root.c_str(), file);
 //printf(">>> filename: [%s]\n", filename);
 
 // send file
 if (!GetFile(conn, filename )) {
  SendError(conn, 404, url);
 }
}
예제 #3
0
int EnvisatFile_SetKeyValueAsDouble( EnvisatFile *self, 
                                     EnvisatFile_HeaderFlag mph_or_sph,
                                     const char *key,
                                     double value )

{
    char format[32], string_value[128];
    const char *prototype_value;
    int		length;

    prototype_value = EnvisatFile_GetKeyValueAsString( self, mph_or_sph, key, NULL);
    if( prototype_value == NULL )
    {
        char	error_buf[2048];

        sprintf( error_buf, 
                 "Unable to set header field \"%s\", field not found.", 
                 key );

        SendError( error_buf );
        return FAILURE;
    }

    length = strlen(prototype_value);
    if( prototype_value[length-4] == 'E' )
    {
        sprintf( format, "%%+%dE", length-4 );
        sprintf( string_value, format, value );
    }
    else
    {
        int	decimals = 0, i;
        for( i = length-1; i > 0; i-- )
        {
            if( prototype_value[i] == '.' )
                break;
            
            decimals++;
        }

        sprintf( format, "%%+0%d.%df", length, decimals );
        sprintf( string_value, format, value );

        if( (int)strlen(string_value) > length )
            string_value[length] = '\0';
    }

    return EnvisatFile_SetKeyValueAsString( self, mph_or_sph, key, string_value );
}
예제 #4
0
bool TParser::Compile(CString _expr, NSGuidesOdp::CFormulaManager& pFManager)
{
   pos = 0;
   expr = _expr;
   curToken = _T("");
   if(root!=NULL)
   {
      DelTree(root);
      root = NULL;
   }

   history.clear();
   CString strTempString(_T("+-*/%^,"));
   while(strTempString.Find(expr[0]) >= 0) expr.Delete(0);

   GetToken();
   if(typToken==PARSER_END) SendError(2);
   root = Expr(pFManager);
   if(typToken!=PARSER_END) SendError(3);

   history.clear();

   return true;
}
bool
DOMStorageDBParent::RecvAsyncClear(const nsCString& aScope)
{
  DOMStorageDBBridge* db = DOMStorageCache::StartDatabase();
  if (!db) {
    return false;
  }

  nsresult rv = db->AsyncClear(NewCache(aScope));
  if (NS_FAILED(rv) && mIPCOpen) {
    mozilla::unused << SendError(rv);
  }

  return true;
}
예제 #6
0
void MessageFactory::ErrorAt(const Exception& ex, const UCS2 *filename, POV_LONG line, POV_LONG column, POV_LONG offset, const char *format, ...)
{
	va_list marker;

	if (ex.frontendnotified())
		throw ex;

	va_start(marker, format);
	SendError(format, marker, filename, line, column, offset);
	va_end(marker);

	pov_base::Exception local_ex(ex);
	local_ex.frontendnotified(true);
	throw local_ex;
}
예제 #7
0
bool TreeSocket::ComparePass(const Link& link, const std::string &theirs)
{
	capab->auth_fingerprint = !link.Fingerprint.empty();
	capab->auth_challenge = !capab->ourchallenge.empty() && !capab->theirchallenge.empty();

	std::string fp;
	if (GetIOHook())
	{
		SocketCertificateRequest req(this, Utils->Creator);
		if (req.cert)
		{
			fp = req.cert->GetFingerprint();
		}
	}

	if (capab->auth_challenge)
	{
		std::string our_hmac = MakePass(link.RecvPass, capab->ourchallenge);

		/* Straight string compare of hashes */
		if (our_hmac != theirs)
			return false;
	}
	else
	{
		/* Straight string compare of plaintext */
		if (link.RecvPass != theirs)
			return false;
	}

	if (capab->auth_fingerprint)
	{
		/* Require fingerprint to exist and match */
		if (link.Fingerprint != fp)
		{
			ServerInstance->SNO->WriteToSnoMask('l',"Invalid SSL fingerprint on link %s: need \"%s\" got \"%s\"",
				link.Name.c_str(), link.Fingerprint.c_str(), fp.c_str());
			SendError("Provided invalid SSL fingerprint " + fp + " - expected " + link.Fingerprint);
			return false;
		}
	}
	else if (!fp.empty())
	{
		ServerInstance->SNO->WriteToSnoMask('l', "SSL fingerprint for link %s is \"%s\". "
			"You can improve security by specifying this in <link:fingerprint>.", link.Name.c_str(), fp.c_str());
	}
	return true;
}
/**
Processes the request for setting absolute volume.

@param aData The absolute volume data to be setted.
*/
void CRemConAbsoluteVolumeTarget::ProcessSetAbsoluteVolume(
		const TDesC8& aData)
	{	
	TInt error;
	RRemConAbsoluteVolumeRequest request;
	TRAP(error, request.ReadL(aData));
	if ( error == KErrNone)
		{
		iObserver.MrcavtoSetAbsoluteVolumeRequest(request.iVolume, 
				request.iMaxVolume);
		}
	else
		{
		SendError(KErrAbsoluteVolumeInternalError, KRemConSetAbsoluteVolume);
		}
	}
예제 #9
0
파일: httpmt.c 프로젝트: Budskii/ulib-win
void SendFile(LPREQUEST lpReq)
{
	//
	// Open the file for reading
	//
	lpReq->hFile = CreateFile(lpReq->szFileName, 
							  GENERIC_READ,
							  FILE_SHARE_READ,
							  NULL,
							  OPEN_EXISTING,
							  FILE_ATTRIBUTE_NORMAL,
							  NULL);
	if (lpReq->hFile == INVALID_HANDLE_VALUE)
	{
		SendMessage(ghwnd,
					guAppMsg,
					HTTP_FILENOTFOUND_MSG,
					(LPARAM)(LPCSTR)lpReq->szFileName);
		// Send "404 Not Found" error
		SendError(lpReq, HTTP_STATUS_NOTFOUND);
		return;
	}

	//
	// Tell the user interface about the file hit
	// (Sending just the request portion -- without
	// the root web directory portion
	//
	SendMessage(ghwnd,
				guAppMsg,
				HTTP_FILEOK_MSG,
				(LPARAM)(LPCSTR)&lpReq->szFileName[strlen(szWebRoot)]);
	//
	// Send the file contents to the client
	//
	SendFileContents(lpReq);

	//
	// Close the file
	//
	if (CloseHandle(lpReq->hFile))
		lpReq->hFile = INVALID_HANDLE_VALUE;
	else
		LogEvent(ghwnd,
				 "Error closing file: %d",
				 GetLastError());
}
예제 #10
0
void MessageFactory::Error(Exception& ex, const char *format, ...)
{
	va_list marker;

	// if the front-end has been told about this exception already, we don't want to tell it again
	// (we presume that the text given by format and its parameters relate to that exception)
	// this form of frontendnotified() sets the notified state of ex
	if (ex.frontendnotified(true))
		throw ex;

	va_start(marker, format);
	SendError(format, marker);
	va_end(marker);

	// Terminate
	throw ex;
}
예제 #11
0
void Pololu::Serial::Interface::send(const std::vector<unsigned char>&
    data) {
  if (handle) {
    int i = 0;

    while (i < data.size()) {
      ssize_t result;
      while ((result = ::write(handle, &data[i], data.size()-i)) == 0);

      if ((result < 0) && (errno != EWOULDBLOCK))
        throw SendError(address);
      else if (result > 0)
        i += result;
    }
  }
  else
    throw OperationError();
}
// The client application has signaled that all attributes have been returned so 
// response can now be sent
EXPORT_C void CRemConMediaInformationTarget::Completed()
	{
	if (!iInProgress)
		{
		return;
		}
	// Finalise response; update number of attributes returned
	iResponse->iNumberAttributes = iResponse->iAttributes.Count();

	//Check the bound of the number of attributes, zero is not permitted
	if (iResponse->iNumberAttributes == 0)
		{
		return SendError(KErrAvrcpMetadataInternalError);
		}
	
	// Allocate a buffer for the formatted message
	RBuf8 messageBuffer;
	if ( messageBuffer.Create(iResponse->Size()) != KErrNone )
		{
		// On OOM drop the message
		iResponse->Close();
		return;
		}
		
	// send the result back to the CT
	TInt error = KErrNone;
	TRAP(error, iResponse->WriteL(messageBuffer));
	if (error == KErrNone)
		{
		InterfaceSelector().SendUnreliable(TUid::Uid(KRemConMediaInformationApiUid),
								EGetElementAttributes, ERemConResponse, messageBuffer);
		}
	
	// Make sure attribute list is reset for next time
	iResponse->Close();
	messageBuffer.Close();
	
	iInProgress = EFalse;
	if (!iMsgQueue.IsEmpty())
		{
		iNextMessageCallBack->CallBack();
		}
	
	}
예제 #13
0
/**************************************
* DispatchRequest
*       Busca el handler para procesar la peticion
**************************************/
int XmlRpcServer::DispatchRequest(TSession *ses)
{
	TRequestInfo *req;

	//Get request info
	SessionGetRequestInfo(ses,(const TRequestInfo**)&req);

	//Log it
	Log("-Dispatching [%s]\n",req->uri);


	//Obtenemos la uri
	string uri = req->uri;

	//Vamos a buscar en orden inverso
	LstHandlers::reverse_iterator it;

	//Check stop
	if (uri.find("/stop")==0)
	{
		//Stop
		Stop();
		//Devolvemos el error
		SendResponse(ses,200,SHUTDOWNMSG,strlen(SHUTDOWNMSG));
		//Exit
		return 1;
	}
	
	//Recorremos la lista
	for (it=lstHandlers.rbegin();it!=lstHandlers.rend();it++)	
	{
		//Si la uri empieza por la base del handler
		if (uri.find((*it).first)==0)
			//Ejecutamos el handler
			return (*it).second->ProcessRequest(req,ses);
	}

	//Devolvemos el error
	SendError(ses,404);

	//Exit
	return 1;
}
예제 #14
0
void MessageFactory::Error(const Exception& ex, const char *format, ...)
{
	va_list marker;

	// if the front-end has been told about this exception already, we don't want to tell it again
	// (we presume that the text given by format and its parameters relate to that exception)
	// this form of frontendnotified() doesn't change the state of ex
	if (ex.frontendnotified())
		throw ex;

	va_start(marker, format);
	SendError(format, marker);
	va_end(marker);

	// now take a copy of ex and set its notification flag, then throw that.
	pov_base::Exception local_ex(ex);
	local_ex.frontendnotified(true);
	throw local_ex;
}
예제 #15
0
TokenPtr Scanner::Next()
{
    while (!Is(0))
    {
        try
        {
            /* Scan next token */
            IgnoreWhiteSpaces();
            return ScanToken();
        }
        catch (const std::exception& err)
        {
            /* Add to error and scan next token */
            SendError(err.what());
            succeeded_ = false;
        }
    }

    return nullptr;
}
예제 #16
0
status_t
ParseRequest(int32 code, void* buffer)
{
	switch (code) {
		case MsgNameToUID:
			return NameToUID(buffer);

		case MsgUIDToName:
			return UIDToName(buffer);

		case MsgNameToGID:
			return NameToGID(buffer);

		case MsgGIDToName:
			return GIDToName(buffer);

		default:
			return SendError(B_BAD_VALUE);
	}
}
예제 #17
0
파일: httpmt.c 프로젝트: Budskii/ulib-win
void SendFileContents(LPREQUEST lpReq)
{
	static BYTE buf[1024];
	DWORD  dwRead;
	BOOL   fRet;

	//
	// Read and send data until EOF
	//
	while(1)
	{
		//
		// Read a buffer full from the file
		//
		fRet = ReadFile(lpReq->hFile,
						buf,
						sizeof(buf),
						&dwRead,
						NULL);
		if (!fRet)
		{
			// Send "404 Not Found" error
			SendError(lpReq, HTTP_STATUS_SERVERERROR);
			break;
		}

		if (dwRead == 0)
			break;

		//
		// Send this buffer to the client
		//
		if (!SendBuffer(lpReq, buf, dwRead))
			break;

		//
		// Add for statistics
		//
		lpReq->dwSend += dwRead;
	}
}
/*
* This will be the first function called once the skill is determined
* as useable.
*/
bool AWormHole::Use(int TargetID)
{
    long ChargeTime;
    float EnergyCost = CalculateEnergy(m_SkillLevel, m_SkillRank);

    //allow the ability to be turned off
    if(m_InUse)
    {
        m_Player->SetCurrentSkill();
        m_DamageTaken = 0.0f;
        return false;
    }

    // Remove the energy
    m_Player->RemoveEnergy(EnergyCost);

    ChargeTime = (long) CalculateChargeUpTime(m_SkillLevel, m_SkillRank);

    m_EffectID = GetNet7TickCount();

    // Make sure no one else can use this skill
    m_InUse = true;

    EnergyCost = CalculateEnergy(m_SkillLevel, m_SkillRank);

    // not enough energy
    if (m_Player->GetEnergyValue() < EnergyCost)
    {
        SendError("Not enough energy!");
        m_InUse = false;
        m_DamageTaken = 0;
        return false;
    }

    // Cast time
    SetTimer(ChargeTime);

    return true;
}
예제 #19
0
파일: GdbStub.c 프로젝트: lersek/edk2
VOID
TransferFromMemToOutBufAndSend (
  IN    UINTN                       Length,
  IN    unsigned char               *Address
  )
{
  // there are Length bytes and every byte is represented as 2 hex chars
  CHAR8   OutBuffer[MAX_BUF_SIZE];
  CHAR8   *OutBufPtr;             // pointer to the output buffer
  CHAR8   Char;

  if (ValidateAddress(Address) == FALSE) {
    SendError(14);
    return;
  }

  OutBufPtr = OutBuffer;
  while (Length > 0) {

    Char = mHexToStr[*Address >> 4];
    if ((Char >= 'A') && (Char <= 'F')) {
      Char = Char - 'A' + 'a';
    }
    *OutBufPtr++ = Char;

    Char = mHexToStr[*Address & 0x0f];
    if ((Char >= 'A') && (Char <= 'F')) {
      Char = Char - 'A' + 'a';
    }
    *OutBufPtr++ = Char;

    Address++;
    Length--;
  }

  *OutBufPtr = '\0' ;  // the end of the buffer
  SendPacket (OutBuffer);
}
예제 #20
0
int ProxyChallenge(struct mansession *s, struct message *m) {
	struct message mo;
	char *actionid;

	actionid = astman_get_header(m, "ActionID");
	if ( strcasecmp("MD5", astman_get_header(m, "AuthType")) ) {
		SendError(s, "Must specify AuthType", actionid);
		return 1;
	}

	if (!*s->challenge)
		snprintf(s->challenge, sizeof(s->challenge), "%d", rand());

	memset(&mo, 0, sizeof(struct message));
	AddHeader(&mo, "Response: Success");
	AddHeader(&mo, "Challenge: %s", s->challenge);
	if( actionid && strlen(actionid) )
		AddHeader(&mo, "ActionID: %s", actionid);

	s->output->write(s, &mo);
	FreeHeaders(&mo);
	return 0;
}
예제 #21
0
/** ‘p n’ 
 Reads the n-th register's value into an output buffer and sends it as a packet 
 @param   SystemContext   Register content at time of the exception
 @param   InBuffer      Pointer to the input buffer received from gdb server
 **/
VOID
ReadNthRegister (
  IN  EFI_SYSTEM_CONTEXT   SystemContext,
  IN  CHAR8                *InBuffer
  )
{
  UINTN RegNumber;
  CHAR8 OutBuffer[17];  // 1 reg=16 hex chars, and the end '\0' (escape seq)
  CHAR8 *OutBufPtr;   // pointer to the output buffer
  
  RegNumber = AsciiStrHexToUintn (&InBuffer[1]);
  
  if ((RegNumber < 0) || (RegNumber >= MaxRegisterCount())) {
    SendError (GDB_EINVALIDREGNUM); 
    return;
  }
  
  OutBufPtr = OutBuffer;
  OutBufPtr = BasicReadRegister(SystemContext, RegNumber, OutBufPtr);
  
  *OutBufPtr = '\0';  // the end of the buffer
  SendPacket (OutBuffer);
}
예제 #22
0
VOID
TransferFromInBufToMem (
  IN    UINTN                       Length,
  IN    unsigned char               *Address,
  IN    CHAR8                       *NewData
  )
{
  CHAR8 c1;
  CHAR8 c2;

  while (Length-- > 0) {
    c1 = (CHAR8)HexCharToInt (*NewData++);
    c2 = (CHAR8)HexCharToInt (*NewData++);

    if ((c1 < 0) || (c2 < 0)) {
      SendError (GDB_EBADMEMDATA);
      return;
    }
    *Address++ = (UINT8)((c1 << 4) + c2);
  }

  SendSuccess();
}
예제 #23
0
void CNetworkPlayer::HandleCommand (const Command & command) {
    if (!m_authenticated) {
        if (command.type() == Command::ConnectRequest) {
            Command out;
            out.set_type(Command::ConnectResponse);
            ConnectResponse * response = out.MutableExtension(ConnectResponse::connectResponse);
            *response->mutable_errorinfo() = ERR(ErrorInfo::OK);
            response->set_playerid(m_playerId);
            SendReliableCommand(out);
            m_authenticated = true;
            for (auto notify : m_notifies) {
                notify->OnNetworkPlayerAuthenticated(this);
            }
        }
        else {
            SendError(ERR(ErrorInfo::NotConnected));
        }
    }
    else {
        for (auto notify : m_notifies) {
            notify->OnNetworkPlayerCommand(this, command);
        }
    }
}
bool ARechargeShields::CanUse(int TargetID, long AbilityID, long SkillID)
{
	// Get the skill level
	m_SkillLevel = (float) m_Player->PlayerIndex()->RPGInfo.Skills.Skill[SkillID].GetLevel();
	m_SkillRank = DetermineSkillRank(AbilityID);
	m_AbilityID = AbilityID;
	m_SkillID = SkillID;
	ObjectManager *om = m_Player->GetObjectManager();

	//Skill does not exist.
	if(m_SkillRank == -1)
	{
		return false;
	}

	// Make sure we are not dead
	if (m_Player->ShipIndex()->GetIsIncapacitated())
	{
		SendError("Can not use this ability while dead!");
		return false;
	}

	// See if we can use this skill
	if (TargetID > 0 && m_SkillRank >= 3 && om)
	{
		Object * Target = om->GetObjectFromID(TargetID);	// Get Target

		if (Target && Target->ObjectType() != m_TargetType)
		{
			SendError("Incorrect target type!");
			return false;
		}

		// See if we are in range
		if (Target->RangeFrom(m_Player->Position()) > CalculateRange(m_SkillLevel, m_SkillRank))
		{
			SendError("Out of range!");
			return false;
		}

		if(g_PlayerMgr->GetPlayer(TargetID)->ShipIndex()->GetIsIncapacitated())
		{
			SendError("Cannot recharge a dead player!");
			return false;
		}
	}

	//If we are prospecting we cannot use this skill
	if (m_Player->Prospecting())
	{
		SendError("Cannot use while prospecting.");
		return false;
	}

	//if we are warping we cannot use the skill
	if (m_Player->WarpDrive())
	{
		SendError("Cannot use while in warp.");
		return false;
	}

	return true;
}
/*
* This will be the first function called once the skill is determined
* as useable.
*/
bool ARechargeShields::Use(int TargetID)
{
	float ChargeTime;
	float EnergyCost;

	if(m_InUse)
	{
		InterruptSkillOnAction(WARPING);
		return false;
	}

	if(m_SkillRank >= 3)
	{
		// Target player
		if(TargetID < 0)
		{
			m_PlayerTarget = m_Player;
		}
		else
		{
			m_PlayerTarget = g_PlayerMgr->GetPlayer(TargetID);
		}

		// If we cant find player return
		if (!m_PlayerTarget)
		{
			m_Player->SetCurrentSkill();
			m_DamageTaken = 0;
			return false;
		}
	}

	if(TargetID <= 0)
	{
		m_PlayerTarget = m_Player;
	}

	m_EffectID = GetNet7TickCount();

	// Make sure no one else can use this skill
	m_InUse = true;

	EnergyCost = CalculateEnergy(m_SkillLevel, m_SkillRank);

	// not enough energy
	if (m_Player->GetEnergyValue() < EnergyCost)
	{
		SendError("Not enough energy!");
		m_Player->SetCurrentSkill();
		m_InUse = false;
		m_DamageTaken = 0;
		return false;
	}

	m_Player->RemoveEnergy(EnergyCost);

	ChargeTime = CalculateChargeUpTime(m_SkillLevel, m_SkillRank);

	//charge up, apply shield charge after charge is finished.
	SetTimer((long)ChargeTime*1000);

	ObjectEffect RechargeChargeEffect;

	memset(&RechargeChargeEffect, 0, sizeof(RechargeChargeEffect));		// Zero out memory

	RechargeChargeEffect.Bitmask = 3;
	RechargeChargeEffect.GameID = m_Player->GameID();
	RechargeChargeEffect.TimeStamp = m_EffectID;
	RechargeChargeEffect.EffectID = m_EffectID;
	RechargeChargeEffect.Duration = (short)ChargeTime;
	RechargeChargeEffect.EffectDescID = 733;
	m_Player->SendObjectEffectRL(&RechargeChargeEffect);

	return true;
}
예제 #26
0
static int EnvisatFile_RewriteHeader( EnvisatFile *self )

{
    int		dsd, dsd_size;

    /* 
     * Rewrite MPH and SPH headers.
     */
    if( S_NameValueList_Rewrite( self->fp, 
                        self->mph_count, self->mph_entries ) == FAILURE )
        return FAILURE;

    if( S_NameValueList_Rewrite( self->fp, 
                        self->sph_count, self->sph_entries ) == FAILURE )
        return FAILURE;

    /*
     * Rewrite DSDs.  We actually have to read each, and reparse to set
     * the individual parameters properly.
     */
    dsd_size = EnvisatFile_GetKeyValueAsInt( self, MPH, "DSD_SIZE", 0 );
    if( dsd_size == 0 )
        return FAILURE;

    for( dsd = 0; dsd < self->ds_count; dsd++ )
    {
        char	*dsd_text;
        int	dsdh_count = 0, key_index;
        EnvisatNameValue **dsdh_entries = NULL;

        dsd_text = (char *) calloc(1,dsd_size+1);
        if( fseek( self->fp, self->dsd_offset + dsd * dsd_size, 
                   SEEK_SET ) != 0 )
        {
            SendError( "fseek() failed in EnvisatFile_RewriteHeader()" );
            return FAILURE;
        }
        
        if( (int) fread( dsd_text, 1, dsd_size, self->fp ) != dsd_size )
        {
            SendError( "fread() failed in EnvisatFile_RewriteHeader()" );
            return FAILURE;
        }

        if( S_NameValueList_Parse( dsd_text, self->dsd_offset + dsd*dsd_size, 
                                   &dsdh_count, &dsdh_entries ) == FAILURE )
            return FAILURE;

        free( dsd_text );

        key_index = S_NameValueList_FindKey( "DS_OFFSET", 
                                             dsdh_count, dsdh_entries );
        if( key_index == -1 )
            continue;

        sprintf( dsdh_entries[key_index]->value, "%+021d", 
                 self->ds_info[dsd]->ds_offset );

        key_index = S_NameValueList_FindKey( "DS_SIZE", 
                                             dsdh_count, dsdh_entries );
        sprintf( dsdh_entries[key_index]->value, "%+021d", 
                 self->ds_info[dsd]->ds_size );

        key_index = S_NameValueList_FindKey( "NUM_DSR", 
                                             dsdh_count, dsdh_entries );
        sprintf( dsdh_entries[key_index]->value, "%+011d", 
                 self->ds_info[dsd]->num_dsr );

        key_index = S_NameValueList_FindKey( "DSR_SIZE", 
                                             dsdh_count, dsdh_entries );
        sprintf( dsdh_entries[key_index]->value, "%+011d", 
                 self->ds_info[dsd]->dsr_size );

        if( S_NameValueList_Rewrite( self->fp, dsdh_count, dsdh_entries )
            == FAILURE )
            return FAILURE;

        S_NameValueList_Destroy( &dsdh_count, &dsdh_entries );
    }

    self->header_dirty = 0;

    return SUCCESS;
}
예제 #27
0
int EnvisatFile_Create( EnvisatFile **self_ptr, 
                        const char *filename, 
                        const char *template_file )

{
    int		template_size;
    char	*template_data;
    FILE	*fp;

    /*
     * Try to open the template file, and read it into memory.
     */

    fp = fopen( template_file, "rb" );

    if( fp == NULL )
    {
        char	error_buf[2048];

        sprintf( error_buf, 
                 "Unable to open file \"%s\" in EnvisatFile_Create().", 
                 template_file );

        SendError( error_buf );
        return FAILURE;
    }

    fseek( fp, 0, SEEK_END );
    template_size = (int) ftell( fp );

    template_data = (char *) malloc(template_size);
    
    fseek( fp, 0, SEEK_SET );
    fread( template_data, template_size, 1, fp );
    fclose( fp );

    /*
     * Try to write the template out to the new filename. 
     */
    
    fp = fopen( filename, "wb" );
    if( fp == NULL )
    {
        char	error_buf[2048];

        sprintf( error_buf, 
                 "Unable to open file \"%s\" in EnvisatFile_Create().", 
                 filename );

        SendError( error_buf );
        return FAILURE;
    }

    fwrite( template_data, template_size, 1, fp );
    fclose( fp );

    free( template_data );

    /*
     * Now just open the file normally. 
     */
    
    return EnvisatFile_Open( self_ptr, filename, "r+" );
}
예제 #28
0
int EnvisatFile_Open( EnvisatFile **self_ptr, 
                      const char *filename, 
                      const char *mode )

{
    FILE	*fp;
    EnvisatFile	*self;
    char	mph_data[1248];
    char	*sph_data, *ds_data;
    int		sph_size, num_dsd, dsd_size, i;

    *self_ptr = NULL;

    /*
     * Check for legal mode argument.  Force to be binary for correct
     * operation on DOS file systems.
     */
    if( strcmp(mode,"r") == 0 )
        mode = "rb";
    else if( strcmp(mode,"r+") == 0 )
        mode = "rb+";
    else
    {
        SendError( "Illegal mode value used in EnvisatFile_Open(), only "
                   "\"r\" and \"r+\" are supported." );
        return FAILURE;
    }

    /*
     * Try to open the file, and report failure. 
     */

    fp = fopen( filename, mode );

    if( fp == NULL )
    {
        char	error_buf[2048];

        sprintf( error_buf, 
                 "Unable to open file \"%s\" in EnvisatFile_Open().", 
                 filename );

        SendError( error_buf );
        return FAILURE;
    }

    /*
     * Create, and initialize the EnvisatFile structure. 
     */
    self = (EnvisatFile *) calloc(sizeof(EnvisatFile),1);
    if( self == NULL )
        return FAILURE;

    self->fp = fp;
    self->filename = strdup( filename );
    self->header_dirty = 0;
    self->updatable = (strcmp(mode,"rb+") == 0);

    /*
     * Read the MPH, and process it as a group of name/value pairs. 
     */

    if( fread( mph_data, 1, MPH_SIZE, fp ) != MPH_SIZE )
    {
        free( self );
        SendError( "fread() for mph failed." );
        return FAILURE;
    }

    mph_data[MPH_SIZE] = '\0';
    if( S_NameValueList_Parse( mph_data, 0, 
                               &(self->mph_count), 
                               &(self->mph_entries) ) == FAILURE )
        return FAILURE;

    /*
     * Is this an incomplete level 0 file?
     */
    if( EnvisatFile_GetKeyValueAsInt( self, MPH, "SPH_SIZE", -1 ) == 0 
        && strncmp(EnvisatFile_GetKeyValueAsString( self, MPH, "PRODUCT", ""),
                   "ASA_IM__0P", 10) == 0 )
    {

        if( EnvisatFile_SetupLevel0( self ) == FAILURE )
        {
            EnvisatFile_Close( self );
            return FAILURE;
        }
        else
        {
            *self_ptr = self;
            return SUCCESS;
        }
    }

    /*
     * Read the SPH, and process it as a group of name/value pairs.  
     */
    sph_size = EnvisatFile_GetKeyValueAsInt( self, MPH, "SPH_SIZE", 0 );

    if( sph_size == 0 )							
    {
        SendError( "File does not appear to have SPH,"
                   " SPH_SIZE not set, or zero." );
        return FAILURE;
    }

    sph_data = (char *) malloc(sph_size + 1 );
    if( sph_data == NULL )
        return FAILURE;

    if( (int) fread( sph_data, 1, sph_size, fp ) != sph_size )
    {
        free( self );
        SendError( "fread() for sph failed." );
        return FAILURE;
    }

    sph_data[sph_size] = '\0';
    ds_data = strstr(sph_data,"DS_NAME");
    if( ds_data != NULL )
    {
        self->dsd_offset = (int) (ds_data - sph_data) + MPH_SIZE;
        *(ds_data-1) = '\0';
    }

    if( S_NameValueList_Parse( sph_data, MPH_SIZE,
                               &(self->sph_count), 
                               &(self->sph_entries) ) == FAILURE )
        return FAILURE;

    /*
     * Parse the Dataset Definitions.
     */
    num_dsd = EnvisatFile_GetKeyValueAsInt( self, MPH, "NUM_DSD", 0 );
    dsd_size = EnvisatFile_GetKeyValueAsInt( self, MPH, "DSD_SIZE", 0 );
    
    if( num_dsd > 0 && ds_data == NULL )
    {
        SendError( "DSDs indicated in MPH, but not found in SPH." );
        return FAILURE;
    }

    self->ds_info = (EnvisatDatasetInfo **) 
        calloc(sizeof(EnvisatDatasetInfo*),num_dsd);
    if( self->ds_info == NULL )
        return FAILURE;

    for( i = 0; i < num_dsd; i++ )
    {
        int	dsdh_count = 0;
        EnvisatNameValue **dsdh_entries = NULL;
        char	*dsd_data;
        EnvisatDatasetInfo *ds_info;

        /*
         * We parse each DSD grouping into a name/value list. 
         */
        dsd_data = ds_data + i * dsd_size;
        dsd_data[dsd_size-1] = '\0';
        
        if( S_NameValueList_Parse( dsd_data, 0, 
                                   &dsdh_count, &dsdh_entries ) == FAILURE )
            return FAILURE;

        /* 
         * Then build the dataset into structure from that. 
         */
        ds_info = (EnvisatDatasetInfo *) calloc(sizeof(EnvisatDatasetInfo),1);

        ds_info->ds_name = strdup( 
            S_NameValueList_FindValue( "DS_NAME", 
                                       dsdh_count, dsdh_entries, "" ));
        ds_info->ds_type = strdup( 
            S_NameValueList_FindValue( "DS_TYPE", 
                                       dsdh_count, dsdh_entries, "" ));
        ds_info->filename = strdup( 
            S_NameValueList_FindValue( "FILENAME", 
                                       dsdh_count, dsdh_entries, "" ));
        ds_info->ds_offset = atoi(
            S_NameValueList_FindValue( "DS_OFFSET", 
                                       dsdh_count, dsdh_entries, "0" ));
        ds_info->ds_size = atoi(
            S_NameValueList_FindValue( "DS_SIZE", 
                                       dsdh_count, dsdh_entries, "0" ));
        ds_info->num_dsr = atoi(
            S_NameValueList_FindValue( "NUM_DSR", 
                                       dsdh_count, dsdh_entries, "0" ));
        ds_info->dsr_size = atoi(
            S_NameValueList_FindValue( "DSR_SIZE", 
                                       dsdh_count, dsdh_entries, "0" ));

        S_NameValueList_Destroy( &dsdh_count, &dsdh_entries );

        self->ds_info[i] = ds_info;
        self->ds_count++;
    }
    
    free( sph_data );

    /*
     * Return successfully.
     */
    *self_ptr = self;

    return SUCCESS;
}
예제 #29
0
int S_NameValueList_Parse( const char *text, int text_offset, 
                           int *entry_count, 
                           EnvisatNameValue ***entries )

{
    const char  *next_text = text;

    /*
     * Loop over each input line in the text block.
     */
    while( *next_text != '\0' )
    {
        char	line[1024];
        int     line_len = 0, equal_index, src_char, line_offset;
        EnvisatNameValue *entry;

        /*
         * Extract one line of text into the "line" buffer, and remove the
         * newline character.  Eat leading spaces.
         */
        while( *next_text == ' ' ) 
        {
            next_text++;
        }
        line_offset = (int) (next_text - text) + text_offset;
        while( *next_text != '\0' && *next_text != '\n' )
        {
            if( line_len > sizeof(line)-1 )
            {
                SendError( "S_NameValueList_Parse(): "
                           "Corrupt line, longer than 1024 characters." );
                return FAILURE;
            }

            line[line_len++] = *(next_text++);
        }

        line[line_len] = '\0';
        if( *next_text == '\n' )
            next_text++;

        /*
         * Blank lines are permitted.  We will skip processing of any line
         * that doesn't have an equal sign, under the assumption it is
         * white space.
         */
        if( strstr( line, "=") == NULL )
            continue;

        /*
         * Create the name/value info structure. 
         */
        entry = (EnvisatNameValue *) calloc(sizeof(EnvisatNameValue),1);
        entry->literal_line = strdup(line);

        /*
         * Capture the key.  We take everything up to the equal sign.  There
         * shouldn't be any white space, but if so, we take it as part of the
         * key.
         */
        equal_index = strstr(line, "=") - line;
        entry->key = (char *) malloc(equal_index+1);
        strncpy( entry->key, line, equal_index );
        entry->key[equal_index] = '\0';
        entry->value_offset = line_offset + equal_index + 1;

        /*
         * If the next character after the equal sign is a double quote, then
         * the value is a string.  Suck out the text between the double quotes.
         */
        if( line[equal_index+1] == '"' )
        {
            for( src_char = equal_index + 2;
                 line[src_char] != '\0' && line[src_char] != '"';
                 src_char++ ) {}

            line[src_char] = '\0';
            entry->value = strdup( line + equal_index + 2 );
            entry->value_offset += 1;
        }

        /*
         * The value is numeric, and may include a units field.
         */
        else
        {
            for( src_char = equal_index + 1; 
                 line[src_char] != '\0' && line[src_char] != '<' 
                     && line[src_char] != ' ';
                 src_char++ ) {}

            /* capture units */
            if( line[src_char] == '<' )
            {
                int dst_char;

                for( dst_char = src_char+1; 
                     line[dst_char] != '>' && line[dst_char] != '\0';
                     dst_char++ ) {}

                line[dst_char] = '\0';
                entry->units = strdup( line + src_char + 1 );
            }

            line[src_char] = '\0';
            entry->value = strdup( line + equal_index + 1 );
        }

        /*
         * Add the entry to the name/value list. 
         */
        (*entry_count)++;
        *entries = (EnvisatNameValue **)
            realloc( *entries, *entry_count * sizeof(EnvisatNameValue*) );

        if( *entries == NULL )
        {
            *entry_count = 0;
            return FAILURE;
        }

        (*entries)[*entry_count-1] = entry;
    }
    
    return SUCCESS;
}
예제 #30
0
void CubeSession::SendError(SessionErrorType errorCode)
{
	SendError(errorCode, false);
}