//* // ======================================================================================================================= // ======================================================================================================================= // SDWORD audio_GetTrackID( const char *fileName ) { //~~~~~~~~~~~~~ TRACK *psTrack; //~~~~~~~~~~~~~ // return if audio not enabled if ( g_bAudioEnabled == false ) { return SAMPLE_NOT_FOUND; } if (fileName == NULL || strlen(fileName) == 0) { debug(LOG_WARNING, "fileName is %s", (fileName == NULL) ? "a NULL pointer" : "empty"); return SAMPLE_NOT_FOUND; } psTrack = (TRACK*)resGetData( "WAV", fileName ); if ( psTrack == NULL ) { return SAMPLE_NOT_FOUND; } return sound_GetTrackID( psTrack ); }
// ------------------------------------------------------------------------------- // Load up all the imds into an array static BOOL multiLoadMiscImds( void ) { UDWORD i=0; BOOL bMoreToProcess=true; char name[15]; // hopefully! /* Go thru' the list */ while(bMoreToProcess) { snprintf(name, sizeof(name), "%s.pie", miscImds[i].pName); /* see if the resource loader can find it */ miscImds[i].pImd = (iIMDShape*)resGetData("IMD",name); /* If it didn't get it then... */ if(!miscImds[i].pImd) { /* Say which one and return false */ debug( LOG_ERROR, "Can't find misselaneous PIE file : %s", miscImds[i].pName ); ASSERT( false,"NULL PIE" ); return(false); } /* If the next one's the end one, then get out now. This is cos strcmp will return 0 only at end of list */ bMoreToProcess = strcmp(miscImds[++i].pName,"END_OF_IMD_LIST"); } return true; }
void anim_SetVals(char szFileName[], UWORD uwAnimID) { /* get track pointer from resource */ BASEANIM *psAnim = (BASEANIM *)resGetData("ANI", szFileName); ASSERT_OR_RETURN(, psAnim, "Cannot find anim %s", szFileName); /* set anim vals */ psAnim->uwID = uwAnimID; sstrcpy(psAnim->szFileName, szFileName); }
/** Retrieves loaded audio files and retrieves a TRACK from them on which some values are set and returns their respective ID numbers * \param fileName the filename of the track * \param loop whether the track should be looped until explicitly stopped * \param volume the volume this track should be played on (range is 0-100) * \param audibleRadius the radius from the source of sound where it can be heard * \return a non-zero value representing the track id number when successful, zero when the file is not found or no more tracks can be loaded (i.e. the limit is reached) */ unsigned int sound_SetTrackVals(const char *fileName, bool loop, unsigned int volume, unsigned int audibleRadius) { unsigned int trackID; TRACK *psTrack; if (fileName == nullptr || strlen(fileName) == 0) // check for empty filename. This is a non fatal error. { debug(LOG_WARNING, "fileName is %s", (fileName == nullptr) ? "a NULL pointer" : "empty"); return 0; } psTrack = (TRACK *)resGetData("WAV", fileName); if (psTrack == nullptr) { debug(LOG_WARNING, "track %s resource not found", fileName); return 0; } // get pre-assigned ID or produce one trackID = audio_GetIDFromStr(fileName); if (trackID == NO_SOUND) { // No pre-assigned ID available, produce one trackID = sound_GetAvailableID(); if (trackID == SAMPLE_NOT_ALLOCATED) { return 0; } } if (g_apTrack[trackID] != nullptr) { debug(LOG_ERROR, "sound_SetTrackVals: track %i already set (filename: \"%s\"\n", trackID, g_apTrack[trackID]->fileName); return 0; } // set track members psTrack->bLoop = loop; psTrack->iVol = volume; psTrack->iAudibleRadius = audibleRadius; // RAII: Make sure to initialize all values (we don't want undefined values)! psTrack->iTime = 0; psTrack->iTimeLastFinished = 0; psTrack->iNumPlaying = 0; // set global g_apTrack[trackID] = psTrack; // increment counter for amount of loaded tracks ++g_iCurTracks; return trackID; }
static bool initMiscImd(unsigned i, unsigned n, const char *nameFormat, unsigned flagType) { char pieName[100]; snprintf(pieName, sizeof(pieName), nameFormat, n); pAssemblyPointIMDs[flagType][i] = (iIMDShape *)resGetData("IMD", pieName); if (!pAssemblyPointIMDs[flagType][i]) { debug(LOG_ERROR, "Can't find assembly point graphic %s for factory", pieName); return false; } return true; }
void anim_SetVals( char szFileName[], UWORD uwAnimID ) { /* get track pointer from resource */ BASEANIM *psAnim = resGetData( "ANI", szFileName ); if ( psAnim == NULL ) { DBERROR( ("anim_SetVals: can't find anim %s\n", szFileName) ); } /* set anim vals */ psAnim->uwID = uwAnimID; strcpy( psAnim->szFileName, szFileName ); }
static unsigned short LoadTextureFile(const char *FileName) { iV_Image *pSprite; unsigned int i; ASSERT_OR_RETURN( 0, resPresent("IMGPAGE", FileName), "Texture file \"%s\" not preloaded.", FileName); pSprite = (iV_Image*)resGetData("IMGPAGE", FileName); debug(LOG_TEXTURE, "Load texture from resource cache: %s (%d, %d)", FileName, pSprite->width, pSprite->height); /* Have we already uploaded this one? */ for (i = 0; i < _TEX_INDEX; ++i) { if (strcasecmp(FileName, _TEX_PAGE[i].name) == 0) { debug(LOG_TEXTURE, "LoadTextureFile: already uploaded"); return _TEX_PAGE[i].id; } } debug(LOG_TEXTURE, "LoadTextureFile: had to upload texture!"); return pie_AddTexPage(pSprite, FileName, 0, 0, true); }
bool frontendInitialise(const char *ResourceFile) { debug(LOG_MAIN, "Initialising frontend : %s", ResourceFile); if(!InitialiseGlobals()) // Initialise all globals and statics everywhere. { return false; } iV_Reset(); // Reset the IV library. if (!scrTabInitialise()) // Initialise the script system { return false; } if (!stringsInitialise()) // Initialise the string system { return false; } if (!objInitialise()) // Initialise the object system { return false; } if (!anim_Init()) { return false; } if ( !animObj_Init( init_ObjectDead ) ) { return false; } if (!allocPlayerPower()) //set up the PlayerPower for each player - this should only be done ONCE now { return false; } debug(LOG_MAIN, "frontEndInitialise: loading resource file ....."); if (!resLoad(ResourceFile, 0)) { //need the object heaps to have been set up before loading in the save game return false; } if (!dispInitialise()) // Initialise the display system { return false; } FrontImages = (IMAGEFILE*)resGetData("IMG", "frontend.img"); /* Shift the interface initialisation here temporarily so that it can pick up the stats after they have been loaded */ if (!intInitialise()) { return false; } // keymappings // clear out any existing mappings keyClearMappings(); keyInitMappings(false); // Set the default uncoloured cursor here, since it looks slightly // better for menus and such. wzSetCursor(CURSOR_DEFAULT); SetFormAudioIDs(-1,ID_SOUND_WINDOWCLOSE); // disable the open noise since distorted in 3dfx builds. initMiscVars(); gameTimeInit(); // hit me with some funky beats.... cdAudio_PlayTrack(SONG_FRONTEND); return true; }
/* Load the feature stats */ BOOL loadFeatureStats(const char *pFeatureData, UDWORD bufferSize) { FEATURE_STATS *psFeature; unsigned int i; char featureName[MAX_STR_LENGTH], GfxFile[MAX_STR_LENGTH], type[MAX_STR_LENGTH]; numFeatureStats = numCR(pFeatureData, bufferSize); // Skip descriptive header if (strncmp(pFeatureData,"Feature ",8)==0) { pFeatureData = strchr(pFeatureData,'\n') + 1; numFeatureStats--; } asFeatureStats = (FEATURE_STATS*)malloc(sizeof(FEATURE_STATS) * numFeatureStats); if (asFeatureStats == NULL) { debug( LOG_FATAL, "Feature Stats - Out of memory" ); abort(); return false; } psFeature = asFeatureStats; for (i = 0; i < numFeatureStats; i++) { UDWORD Width, Breadth; int damageable = 0, tileDraw = 0, allowLOS = 0, visibleAtStart = 0; memset(psFeature, 0, sizeof(FEATURE_STATS)); featureName[0] = '\0'; GfxFile[0] = '\0'; type[0] = '\0'; //read the data into the storage - the data is delimeted using comma's sscanf(pFeatureData, "%[^','],%d,%d,%d,%d,%d,%[^','],%[^','],%d,%d,%d", featureName, &Width, &Breadth, &damageable, &psFeature->armourValue, &psFeature->body, GfxFile, type, &tileDraw, &allowLOS, &visibleAtStart); psFeature->damageable = damageable; psFeature->tileDraw = tileDraw; psFeature->allowLOS = allowLOS; psFeature->visibleAtStart = visibleAtStart; // These are now only 16 bits wide - so we need to copy them psFeature->baseWidth = Width; psFeature->baseBreadth = Breadth; psFeature->pName = allocateName(featureName); if (!psFeature->pName) { return false; } if (psFeature->damageable && psFeature->body == 0) { debug(LOG_ERROR, "The feature %s, ref %d, is damageable, but has no body points! The files need to be updated / fixed. " \ "Assigning 1 body point to feature.", psFeature->pName, psFeature->ref); psFeature->body = 1; } //determine the feature type featureType(psFeature, type); //and the oil resource - assumes only one! if (psFeature->subType == FEAT_OIL_RESOURCE) { oilResFeature = psFeature; } //get the IMD for the feature psFeature->psImd = (iIMDShape *) resGetData("IMD", GfxFile); if (psFeature->psImd == NULL) { debug( LOG_ERROR, "Cannot find the feature PIE for record %s", getName( psFeature->pName ) ); return false; } psFeature->ref = REF_FEATURE_START + i; //increment the pointer to the start of the next record pFeatureData = strchr(pFeatureData,'\n') + 1; //increment the list to the start of the next storage block psFeature++; } return true; }
// Read bitmaps used by the interface. // bool imageInitBitmaps() { IntImages = (IMAGEFILE *)resGetData("IMG", "intfac.img"); return true; }
error_t httpSendResponse(HttpConnection *connection, const char_t *uri) { #if (HTTP_SERVER_FS_SUPPORT == ENABLED) error_t error; uint32_t length; size_t n; FsFile *file; //Retrieve the full pathname httpGetAbsolutePath(connection, uri, connection->buffer, HTTP_SERVER_BUFFER_SIZE); //Retrieve the size of the specified file error = fsGetFileSize(connection->buffer, &length); //The specified URI cannot be found? if(error) return ERROR_NOT_FOUND; //Open the file for reading file = fsOpenFile(connection->buffer, FS_FILE_MODE_READ); //Failed to open the file? if(!file) return ERROR_NOT_FOUND; #else error_t error; size_t length; uint8_t *data; //Retrieve the full pathname httpGetAbsolutePath(connection, uri, connection->buffer, HTTP_SERVER_BUFFER_SIZE); //Get the resource data associated with the URI error = resGetData(connection->buffer, &data, &length); //The specified URI cannot be found? if(error) return error; #endif //Format HTTP response header connection->response.statusCode = 200; connection->response.contentType = mimeGetType(uri); connection->response.chunkedEncoding = FALSE; connection->response.contentLength = length; //Send the header to the client error = httpWriteHeader(connection); //Any error to report? if(error) { #if (HTTP_SERVER_FS_SUPPORT == ENABLED) //Close the file fsCloseFile(file); #endif //Return status code return error; } #if (HTTP_SERVER_FS_SUPPORT == ENABLED) //Send response body while(length > 0) { //Limit the number of bytes to read at a time n = MIN(length, HTTP_SERVER_BUFFER_SIZE); //Read data from the specified file error = fsReadFile(file, connection->buffer, n, &n); //End of input stream? if(error) break; //Send data to the client error = httpWriteStream(connection, connection->buffer, n); //Any error to report? if(error) break; //Decrement the count of remaining bytes to be transferred length -= n; } //Close the file fsCloseFile(file); //Successful file transfer? if(length == 0 && error == ERROR_END_OF_STREAM) { //Properly close the output stream error = httpCloseStream(connection); } #else //Send response body error = httpWriteStream(connection, data, length); //Any error to report? if(error) return error; //Properly close output stream error = httpCloseStream(connection); #endif //Return status code return error; }
// load the context information for the script system static BOOL eventLoadContext(const SDWORD version, char *pBuffer, UDWORD *pSize, BOOL bHashed) { UDWORD size, valSize,stringLen; SDWORD numVars, i, numContext, context; SCRIPT_CONTEXT *psCCont; INTERP_TYPE type; SCR_VAL_LOAD loadFunc; char *pPos; char *pScriptID = NULL; UDWORD hashedName; SCRIPT_CODE *psCode; CONTEXT_RELEASE release; INTERP_VAL *psVal, data; size = 0; pPos = pBuffer; // get the number of contexts in the save file endian_sword((SWORD*)pPos); numContext = *((SWORD *)pPos); pPos += sizeof(SWORD); size += sizeof(SWORD); // go through the contexts for(context=0; context < numContext; context += 1) { if(bHashed) { endian_udword((UDWORD*)pPos); hashedName = *((UDWORD*)pPos); psCode = (SCRIPT_CODE*)resGetDataFromHash("SCRIPT", hashedName); pPos += sizeof(UDWORD); } else { // get the script code pScriptID = (char *)pPos; psCode = (SCRIPT_CODE*)resGetData("SCRIPT", pScriptID); pPos += strlen(pScriptID) + 1; } // check the number of variables endian_sword((SWORD*)pPos); numVars = psCode->numGlobals + psCode->arraySize; if (numVars != *((SWORD*)pPos)) { ASSERT(false, "Context %d of %d: Number of context variables (%d) does not match the script code (%d)", context, numContext, numVars, *((SWORD*)pPos)); return false; } pPos += sizeof(SWORD); release = (CONTEXT_RELEASE)*pPos; pPos += sizeof(UBYTE); // create the context if (!eventNewContext(psCode, release, &psCCont)) { return false; } // bit of a hack this - note the id of the context to link it to the triggers psContList->id = (SWORD)context; if(bHashed) { size += sizeof(UDWORD) + sizeof(SWORD) + sizeof(UBYTE); } else { size += strlen(pScriptID) + 1 + sizeof(SWORD) + sizeof(UBYTE); } // set the context variables for(i=0; i < numVars; i+= 1) { // get the variable type endian_sword((SWORD*)pPos); type = (INTERP_TYPE) *((SWORD*)pPos); pPos += sizeof(SWORD); size += sizeof(SWORD); // get the variable value if (type < VAL_USERTYPESTART) { data.type = type; endian_udword((UDWORD*)pPos); switch (type) { case VAL_BOOL: data.v.bval = *((BOOL*)pPos); pPos += sizeof(BOOL); size += sizeof(BOOL); break; case VAL_FLOAT: data.v.fval = *((float*)pPos); pPos += sizeof(float); size += sizeof(float); break; case VAL_INT: case VAL_TRIGGER: case VAL_EVENT: case VAL_VOID: case VAL_OPCODE: case VAL_PKOPCODE: data.v.ival = *((UDWORD *)pPos); pPos += sizeof(UDWORD); size += sizeof(UDWORD); break; case VAL_STRING: data.v.sval = (char*)malloc(MAXSTRLEN); strcpy(data.v.sval, "\0"); stringLen = *((UDWORD *)pPos); //read string length pPos += sizeof(UDWORD); size += sizeof(UDWORD); //load string if(stringLen > 0) { strlcpy(data.v.sval, (char *)pPos, MIN(stringLen + 1, MAXSTRLEN)); pPos += stringLen; size += stringLen; } break; case VAL_OBJ_GETSET: /* FIXME: saving pointer on disk! */ data.v.pObjGetSet = *((SCRIPT_VARFUNC*)pPos); pPos += sizeof(SCRIPT_VARFUNC); size += sizeof(SCRIPT_VARFUNC); break; case VAL_FUNC_EXTERN: /* FIXME: saving pointer on disk! */ data.v.pFuncExtern = *((SCRIPT_FUNC*)pPos); pPos += sizeof(SCRIPT_FUNC); size += sizeof(SCRIPT_FUNC); break; default: ASSERT( false, "eventLoadContext: invalid internal type" ); } // set the value in the context if (!eventSetContextVar(psCCont, (UDWORD)i, &data)) { debug( LOG_FATAL, "eventLoadContext: couldn't set variable value" ); abort(); return false; } } else { // user defined type loadFunc = asScrTypeTab[type - VAL_USERTYPESTART].loadFunc; ASSERT( loadFunc != NULL, "eventLoadContext: no load function for type %d\n", type ); endian_uword((UWORD*)pPos); valSize = *((UWORD *)pPos); pPos += sizeof(UWORD); size += sizeof(UWORD); // get the value pointer so that the loadFunc can write directly // into the variables data space. if (!eventGetContextVal(psCCont, (UDWORD)i, &psVal)) { debug( LOG_FATAL, "eventLoadContext: couldn't find variable in context" ); abort(); return false; } if (!loadFunc(version, psVal, pPos, valSize)) { debug( LOG_FATAL, "eventLoadContext: couldn't get variable value" ); abort(); return false; } pPos += valSize; size += valSize; } } } *pSize = size; return true; }
int_t main(void) { error_t error; NetInterface *interface; OsTask *task; MacAddr macAddr; #if (APP_USE_DHCP == DISABLED) Ipv4Addr ipv4Addr; #endif #if (APP_USE_SLAAC == DISABLED) Ipv6Addr ipv6Addr; #endif //Initialize kernel osInitKernel(); //Configure debug UART debugInit(115200); //Start-up message TRACE_INFO("\r\n"); TRACE_INFO("******************************\r\n"); TRACE_INFO("*** CycloneSSL Client Demo ***\r\n"); TRACE_INFO("******************************\r\n"); TRACE_INFO("Copyright: 2010-2015 Oryx Embedded SARL\r\n"); TRACE_INFO("Compiled: %s %s\r\n", __DATE__, __TIME__); TRACE_INFO("Target: AT32UC3A0512\r\n"); TRACE_INFO("\r\n"); //Configure I/Os ioInit(); //Initialize LCD display /*GLCD_Init(); GLCD_SetBackColor(Blue); GLCD_SetTextColor(White); GLCD_Clear(Blue);*/ //Welcome message lcdSetCursor(0, 0); printf("SSL Client Demo\r\n"); //Generate a random seed //PRNG initialization error = yarrowInit(&yarrowContext); //Any error to report? if(error) { //Debug message TRACE_ERROR("Failed to initialize PRNG!\r\n"); } //Properly seed the PRNG error = yarrowSeed(&yarrowContext, seed, sizeof(seed)); //Any error to report? if(error) { //Debug message TRACE_ERROR("Failed to seed PRNG!\r\n"); } //Debug message TRACE_INFO("Loading credentials...\r\n"); //Start of exception handling block do { //Load trusted CA certificates error = resGetData(APP_CA_CERT_BUNDLE, (uint8_t **) &trustedCaList, &trustedCaListLength); //Any error to report? if(error) break; //Load client's certificate error = resGetData(APP_CLIENT_CERT, (uint8_t **) &clientCert, &clientCertLength); //Any error to report? if(error) break; //Load client's private key error = resGetData(APP_CLIENT_PRIVATE_KEY, (uint8_t **) &clientPrivateKey, &clientPrivateKeyLength); //Any error to report? if(error) break; //End of exception handling block } while(0); //Check error code if(error) { //Debug message TRACE_ERROR("Failed to load credentials!\r\n"); } //TCP/IP stack initialization error = netInit(); //Any error to report? if(error) { //Debug message TRACE_ERROR("Failed to initialize TCP/IP stack!\r\n"); } //Configure the first Ethernet interface interface = &netInterface[0]; //Set interface name netSetInterfaceName(interface, "eth0"); //Set host name netSetHostname(interface, "SSLClientDemo"); //Select the relevant network adapter netSetDriver(interface, &avr32EthDriver); netSetPhyDriver(interface, &dp83848PhyDriver); //Set host MAC address macStringToAddr(APP_MAC_ADDR, &macAddr); netSetMacAddr(interface, &macAddr); //Initialize network interface error = netConfigInterface(interface); //Any error to report? if(error) { //Debug message TRACE_ERROR("Failed to configure interface %s!\r\n", interface->name); } #if (IPV4_SUPPORT == ENABLED) #if (APP_USE_DHCP == ENABLED) //Get default settings dhcpClientGetDefaultSettings(&dhcpClientSettings); //Set the network interface to be configured by DHCP dhcpClientSettings.interface = interface; //Disable rapid commit option dhcpClientSettings.rapidCommit = FALSE; //DHCP client initialization error = dhcpClientInit(&dhcpClientContext, &dhcpClientSettings); //Failed to initialize DHCP client? if(error) { //Debug message TRACE_ERROR("Failed to initialize DHCP client!\r\n"); } //Start DHCP client error = dhcpClientStart(&dhcpClientContext); //Failed to start DHCP client? if(error) { //Debug message TRACE_ERROR("Failed to start DHCP client!\r\n"); } #else //Set IPv4 host address ipv4StringToAddr(APP_IPV4_HOST_ADDR, &ipv4Addr); ipv4SetHostAddr(interface, ipv4Addr); //Set subnet mask ipv4StringToAddr(APP_IPV4_SUBNET_MASK, &ipv4Addr); ipv4SetSubnetMask(interface, ipv4Addr); //Set default gateway ipv4StringToAddr(APP_IPV4_DEFAULT_GATEWAY, &ipv4Addr); ipv4SetDefaultGateway(interface, ipv4Addr); //Set primary and secondary DNS servers ipv4StringToAddr(APP_IPV4_PRIMARY_DNS, &ipv4Addr); ipv4SetDnsServer(interface, 0, ipv4Addr); ipv4StringToAddr(APP_IPV4_SECONDARY_DNS, &ipv4Addr); ipv4SetDnsServer(interface, 1, ipv4Addr); #endif #endif #if (IPV6_SUPPORT == ENABLED) #if (APP_USE_SLAAC == ENABLED) //Get default settings slaacGetDefaultSettings(&slaacSettings); //Set the network interface to be configured slaacSettings.interface = interface; //SLAAC initialization error = slaacInit(&slaacContext, &slaacSettings); //Failed to initialize SLAAC? if(error) { //Debug message TRACE_ERROR("Failed to initialize SLAAC!\r\n"); } //Start IPv6 address autoconfiguration process error = slaacStart(&slaacContext); //Failed to start SLAAC process? if(error) { //Debug message TRACE_ERROR("Failed to start SLAAC!\r\n"); } #else //Set link-local address ipv6StringToAddr(APP_IPV6_LINK_LOCAL_ADDR, &ipv6Addr); ipv6SetLinkLocalAddr(interface, &ipv6Addr); //Set IPv6 prefix ipv6StringToAddr(APP_IPV6_PREFIX, &ipv6Addr); ipv6SetPrefix(interface, &ipv6Addr, APP_IPV6_PREFIX_LENGTH); //Set global address ipv6StringToAddr(APP_IPV6_GLOBAL_ADDR, &ipv6Addr); ipv6SetGlobalAddr(interface, &ipv6Addr); //Set router ipv6StringToAddr(APP_IPV6_ROUTER, &ipv6Addr); ipv6SetRouter(interface, &ipv6Addr); //Set primary and secondary DNS servers ipv6StringToAddr(APP_IPV6_PRIMARY_DNS, &ipv6Addr); ipv6SetDnsServer(interface, 0, &ipv6Addr); ipv6StringToAddr(APP_IPV6_SECONDARY_DNS, &ipv6Addr); ipv6SetDnsServer(interface, 1, &ipv6Addr); #endif #endif //Create user task task = osCreateTask("User Task", userTask, NULL, 850, 1); //Failed to create the task? if(task == OS_INVALID_HANDLE) { //Debug message TRACE_ERROR("Failed to create task!\r\n"); } //Create a task to blink the LED task = osCreateTask("Blink", blinkTask, NULL, 500, 1); //Failed to create the task? if(task == OS_INVALID_HANDLE) { //Debug message TRACE_ERROR("Failed to create task!\r\n"); } //Start the execution of tasks osStartKernel(); //This function should never return return 0; }
error_t ssiExecuteScript(HttpConnection *connection, const char_t *uri, uint_t level) { error_t error; size_t length; #if (HTTP_SERVER_FS_SUPPORT == ENABLED) bool_t more; uint_t pos; uint_t n; char_t *buffer; FsFile *file; #else uint_t i; uint_t j; char_t *data; #endif //Recursion limit exceeded? if(level >= HTTP_SERVER_SSI_MAX_RECURSION) return NO_ERROR; //Retrieve the full pathname httpGetAbsolutePath(connection, uri, connection->buffer, HTTP_SERVER_BUFFER_SIZE); #if (HTTP_SERVER_FS_SUPPORT == ENABLED) //Open the file for reading file = fsOpenFile(connection->buffer, FS_FILE_MODE_READ); //Failed to open the file? if(!file) return ERROR_NOT_FOUND; //Allocate a memory buffer buffer = osAllocMem(HTTP_SERVER_BUFFER_SIZE); //Failed to allocate memory? if(!buffer) { //Close the file fsCloseFile(file); //Report an error return ERROR_OUT_OF_MEMORY; } #else //Get the resource data associated with the URI error = resGetData(connection->buffer, (uint8_t **) &data, &length); //The specified URI cannot be found? if(error) return error; #endif //Send the HTTP response header before executing the script if(!level) { //Format HTTP response header connection->response.statusCode = 200; connection->response.contentType = mimeGetType(uri); connection->response.chunkedEncoding = TRUE; //Send the header to the client error = httpWriteHeader(connection); //Any error to report? if(error) { #if (HTTP_SERVER_FS_SUPPORT == ENABLED) //Close the file fsCloseFile(file); //Release memory buffer osFreeMem(buffer); #endif //Return status code return error; } } #if (HTTP_SERVER_FS_SUPPORT == ENABLED) //Point to the beginning of the buffer pos = 0; length = 0; //This flag indicates whether data should be read more = TRUE; //Parse the specified file while(1) { //Read more data if needed if(more) { //Read data from the specified file error = fsReadFile(file, buffer + pos + length, HTTP_SERVER_BUFFER_SIZE - (pos + length), &n); //End of input stream? if(error) { //Purge data buffer error = httpWriteStream(connection, buffer + pos, length); //Exit immediately break; } //Adjust the length of the buffer length += n; //Clear flag more = FALSE; } //Search for any SSI tags error = ssiSearchTag(buffer + pos, length, "<!--#", 5, &n); //Full match? if(error == NO_ERROR) { //Send the part of the file that precedes the tag error = httpWriteStream(connection, buffer + pos, n); //Failed to send data? if(error) break; //Advance data pointer pos += n; length -= n; //Search for the comment terminator error = ssiSearchTag(buffer + pos + 5, length - 5, "-->", 3, &n); //Full match? if(error == NO_ERROR) { //Advance data pointer over the opening identifier pos += 5; length -= 5; //Process SSI directive error = ssiProcessCommand(connection, buffer + pos, n, uri, level); //Any error to report? if(error) break; //Advance data pointer over the SSI tag pos += n + 3; length -= n + 3; } //No match or partial match? else { if(pos > 0) { //Move the remaining bytes to the start of the buffer memmove(buffer, buffer + pos, length); //Rewind to the beginning of the buffer pos = 0; //More data are needed more = TRUE; } else { //Send data to the client error = httpWriteStream(connection, buffer + pos, length); //Any error to report? if(error) break; //Rewind to the beginning of the buffer pos = 0; length = 0; //More data are needed more = TRUE; } } } //Partial match? else if(error == ERROR_PARTIAL_MATCH) { //Send the part of the file that precedes the tag error = httpWriteStream(connection, buffer + pos, n); //Failed to send data? if(error) break; //Advance data pointer pos += n; length -= n; //Move the remaining bytes to the start of the buffer memmove(buffer, buffer + pos, length); //Rewind to the beginning of the buffer pos = 0; //More data are needed more = TRUE; } //No match? else { //Send data to the client error = httpWriteStream(connection, buffer + pos, length); //Any error to report? if(error) break; //Rewind to the beginning of the buffer pos = 0; length = 0; //More data are needed more = TRUE; } } //Close the file fsCloseFile(file); //Release memory buffer osFreeMem(buffer); //Properly close the output stream if(!level && error == NO_ERROR) error = httpCloseStream(connection); #else //Parse the specified file while(length > 0) { //Search for any SSI tags error = ssiSearchTag(data, length, "<!--#", 5, &i); //Opening identifier found? if(!error) { //Search for the comment terminator error = ssiSearchTag(data + i + 5, length - i - 5, "-->", 3, &j); } //Check whether a valid SSI tag has been found? if(!error) { //Send the part of the file that precedes the tag error = httpWriteStream(connection, data, i); //Failed to send data? if(error) return error; //Advance data pointer over the opening identifier data += i + 5; length -= i + 5; //Process SSI directive error = ssiProcessCommand(connection, data, j, uri, level); //Any error to report? if(error) return error; //Advance data pointer over the SSI tag data += j + 3; length -= j + 3; } else { //Send the rest of the file error = httpWriteStream(connection, data, length); //Failed to send data? if(error) return error; //Advance data pointer data += length; length = 0; } } //Properly close the output stream if(!level) error = httpCloseStream(connection); #endif //Return status code return error; }
error_t ssiProcessIncludeCommand(HttpConnection *connection, const char_t *tag, size_t length, const char_t *uri, uint_t level) { error_t error; char_t *separator; char_t *attribute; char_t *value; char_t *path; char_t *p; //Discard invalid SSI directives if(length < 7 || length >= HTTP_SERVER_BUFFER_SIZE) return ERROR_INVALID_TAG; //Skip the SSI include command (7 bytes) memcpy(connection->buffer, tag + 7, length - 7); //Ensure the resulting string is NULL-terminated connection->buffer[length - 7] = '\0'; //Check whether a separator is present separator = strchr(connection->buffer, '='); //Separator not found? if(!separator) return ERROR_INVALID_TAG; //Split the tag *separator = '\0'; //Get attribute name and value attribute = strTrimWhitespace(connection->buffer); value = strTrimWhitespace(separator + 1); //Remove leading simple or double quote if(value[0] == '\'' || value[0] == '\"') value++; //Get the length of the attribute value length = strlen(value); //Remove trailing simple or double quote if(length > 0) { if(value[length - 1] == '\'' || value[length - 1] == '\"') value[length - 1] = '\0'; } //Check the length of the filename if(strlen(value) > HTTP_SERVER_URI_MAX_LEN) return ERROR_INVALID_TAG; //The file parameter defines the included file as relative to the document path if(!strcasecmp(attribute, "file")) { //Allocate a buffer to hold the path to the file to be included path = osAllocMem(strlen(uri) + strlen(value) + 1); //Failed to allocate memory? if(!path) return ERROR_OUT_OF_MEMORY; //Copy the path identifying the script file being processed strcpy(path, uri); //Search for the last slash character p = strrchr(path, '/'); //Remove the filename from the path if applicable if(p) strcpy(p + 1, value); else strcpy(path, value); } //The virtual parameter defines the included file as relative to the document root else if(!strcasecmp(attribute, "virtual")) { //Copy the absolute path path = strDuplicate(value); //Failed to duplicate the string? if(!path) return ERROR_OUT_OF_MEMORY; } //Unknown parameter... else { //Report an error return ERROR_INVALID_TAG; } //Use server-side scripting to dynamically generate HTML code? if(httpCompExtension(value, ".stm") || httpCompExtension(value, ".shtm") || httpCompExtension(value, ".shtml")) { //SSI processing (Server Side Includes) error = ssiExecuteScript(connection, path, level + 1); } else { #if (HTTP_SERVER_FS_SUPPORT == ENABLED) FsFile *file; //Retrieve the full pathname httpGetAbsolutePath(connection, path, connection->buffer, HTTP_SERVER_BUFFER_SIZE); //Open the file for reading file = fsOpenFile(connection->buffer, FS_FILE_MODE_READ); //Successful operation? if(file) { //Send the contents of the requested file while(1) { //Read data from the specified file error = fsReadFile(file, connection->buffer, HTTP_SERVER_BUFFER_SIZE, &length); //End of input stream? if(error) break; //Send data to the client error = httpWriteStream(connection, connection->buffer, length); //Any error to report? if(error) break; } //Close the file fsCloseFile(file); //Successful file transfer? if(error == ERROR_END_OF_STREAM) error = NO_ERROR; } else { //The specified URI cannot be found error = ERROR_NOT_FOUND; } #else uint8_t *data; //Retrieve the full pathname httpGetAbsolutePath(connection, path, connection->buffer, HTTP_SERVER_BUFFER_SIZE); //Get the resource data associated with the file error = resGetData(connection->buffer, &data, &length); //Send the contents of the requested file if(!error) error = httpWriteStream(connection, data, length); #endif } //Cannot found the specified resource? if(error == ERROR_NOT_FOUND) error = ERROR_INVALID_TAG; //Release previously allocated memory osFreeMem(path); //return status code return error; }
int iV_TexLoadNew( char *path, char *filename, int type, iBool palkeep, iBool bColourKeyed ) { char fname[MAX_FILE_PATH]; int i; iSprite *s; TEXTUREPAGE *TextPage; // pointer to the resource texture page structure ... palette stuff is BACK !!!!! // If we are in the BSP or PIEBIN tool, then just added it into the array and exit #ifdef PIETOOL return pie_AddBMPtoTexPages(NULL, filename, type, bColourKeyed, TRUE); #endif /* If it's not a resource - use old way! - PSX does not need this check because it MUST have been loaded allready by the resource loader */ if(!resPresent("TEXPAGE",filename)) { DBERROR(("Texture not in resources; %s.\n", filename)); return(iV_TexLoad( path, filename, type, palkeep, bColourKeyed )); } /* Ensure upper case for tex file names */ ASSERT ((strlen(filename)<MAX_FILE_PATH,"Texture file path too long")); /* Get a copy of the name */ // if we convert it to upper case ... the resource loading will not work for (i = 0; i < (int)strlen(filename); i++) { fname[i] = filename[i]; } /* Terminate it */ fname[i] = '\0'; /* Back to beginning */ i = 0; /* Have we already loaded this one then? */ while (i<_TEX_INDEX) { if (stricmp(fname,_TEX_PAGE[i].name) == 0) { /* Send back 3dfx texpage number if we're on 3dfx - they're NOT the same */ if(rendSurface.usr == REND_GLIDE_3DFX) { return(_TEX_PAGE[i].textPage3dfx); } else { /* Otherwise send back the software one */ return i; } } i++; } /* Get a pointer to the texpage in memory - we KNOW it's there from the check at start */ TextPage = (TEXTUREPAGE *)resGetData("TEXPAGE",filename); s = TextPage->Texture; return pie_AddBMPtoTexPages(s, fname, type, bColourKeyed, TRUE); }