/*******************************************************************************
 * Generic function to load an image into the trusted RAM,
 * given a name, extents of free memory & whether the image should be loaded at
 * the bottom or top of the free memory. It updates the memory layout if the
 * load is successful. It also updates the image information and the entry point
 * information in the params passed
 ******************************************************************************/
int load_image(meminfo_t *mem_layout,
			 const char *image_name,
			 unsigned int load_type,
			 unsigned long fixed_addr,
			 image_info_t *image_data,
			 entry_point_info_t *entry_point_info)
{
	uintptr_t dev_handle;
	uintptr_t image_handle;
	uintptr_t image_spec;
	unsigned long temp_image_base = 0;
	unsigned long image_base = 0;
	long offset = 0;
	size_t image_size = 0;
	size_t bytes_read = 0;
	int io_result = IO_FAIL;

	assert(mem_layout != NULL);
	assert(image_name != NULL);
	assert(image_data->h.version >= VERSION_1);

	/* Obtain a reference to the image by querying the platform layer */
	io_result = plat_get_image_source(image_name, &dev_handle, &image_spec);
	if (io_result != IO_SUCCESS) {
		WARN("Failed to obtain reference to image '%s' (%i)\n",
			image_name, io_result);
		return io_result;
	}

	/* Attempt to access the image */
	io_result = io_open(dev_handle, image_spec, &image_handle);
	if (io_result != IO_SUCCESS) {
		WARN("Failed to access image '%s' (%i)\n",
			image_name, io_result);
		return io_result;
	}

	/* Find the size of the image */
	io_result = io_size(image_handle, &image_size);
	if ((io_result != IO_SUCCESS) || (image_size == 0)) {
		WARN("Failed to determine the size of the image '%s' file (%i)\n",
			image_name, io_result);
		goto exit;
	}

	/* See if we have enough space */
	if (image_size > mem_layout->free_size) {
		WARN("Cannot load '%s' file: Not enough space.\n",
			image_name);
		dump_load_info(0, image_size, mem_layout);
		goto exit;
	}

	switch (load_type) {

	case TOP_LOAD:

	  /* Load the image in the top of free memory */
	  temp_image_base = mem_layout->free_base + mem_layout->free_size;
	  temp_image_base -= image_size;

	  /* Page align base address and check whether the image still fits */
	  image_base = page_align(temp_image_base, DOWN);
	  assert(image_base <= temp_image_base);

	  if (image_base < mem_layout->free_base) {
		WARN("Cannot load '%s' file: Not enough space.\n",
			image_name);
		dump_load_info(image_base, image_size, mem_layout);
		io_result = -ENOMEM;
		goto exit;
	  }

	  /* Calculate the amount of extra memory used due to alignment */
	  offset = temp_image_base - image_base;

	  break;

	case BOT_LOAD:

	  /* Load the BL2 image in the bottom of free memory */
	  temp_image_base = mem_layout->free_base;
	  image_base = page_align(temp_image_base, UP);
	  assert(image_base >= temp_image_base);

	  /* Page align base address and check whether the image still fits */
	  if (image_base + image_size >
	      mem_layout->free_base + mem_layout->free_size) {
		WARN("Cannot load '%s' file: Not enough space.\n",
		  image_name);
		dump_load_info(image_base, image_size, mem_layout);
		io_result = -ENOMEM;
		goto exit;
	  }

	  /* Calculate the amount of extra memory used due to alignment */
	  offset = image_base - temp_image_base;

	  break;

	default:
	  assert(0);

	}

	/*
	 * Some images must be loaded at a fixed address, not a dynamic one.
	 *
	 * This has been implemented as a hack on top of the existing dynamic
	 * loading mechanism, for the time being.  If the 'fixed_addr' function
	 * argument is different from zero, then it will force the load address.
	 * So we still have this principle of top/bottom loading but the code
	 * determining the load address is bypassed and the load address is
	 * forced to the fixed one.
	 *
	 * This can result in quite a lot of wasted space because we still use
	 * 1 sole meminfo structure to represent the extents of free memory,
	 * where we should use some sort of linked list.
	 *
	 * E.g. we want to load BL2 at address 0x04020000, the resulting memory
	 *      layout should look as follows:
	 * ------------ 0x04040000
	 * |          |  <- Free space (1)
	 * |----------|
	 * |   BL2    |
	 * |----------| 0x04020000
	 * |          |  <- Free space (2)
	 * |----------|
	 * |   BL1    |
	 * ------------ 0x04000000
	 *
	 * But in the current hacky implementation, we'll need to specify
	 * whether BL2 is loaded at the top or bottom of the free memory.
	 * E.g. if BL2 is considered as top-loaded, the meminfo structure
	 * will give the following view of the memory, hiding the chunk of
	 * free memory above BL2:
	 * ------------ 0x04040000
	 * |          |
	 * |          |
	 * |   BL2    |
	 * |----------| 0x04020000
	 * |          |  <- Free space (2)
	 * |----------|
	 * |   BL1    |
	 * ------------ 0x04000000
	 */
	if (fixed_addr != 0) {
		/* Load the image at the given address. */
		image_base = fixed_addr;

		/* Check whether the image fits. */
		if ((image_base < mem_layout->free_base) ||
		    (image_base + image_size >
		       mem_layout->free_base + mem_layout->free_size)) {
			WARN("Cannot load '%s' file: Not enough space.\n",
				image_name);
			dump_load_info(image_base, image_size, mem_layout);
			io_result = -ENOMEM;
			goto exit;
		}

		/* Check whether the fixed load address is page-aligned. */
		if (!is_page_aligned(image_base)) {
			WARN("Cannot load '%s' file at unaligned address 0x%lx\n",
				image_name, fixed_addr);
			io_result = -ENOMEM;
			goto exit;
		}

		/*
		 * Calculate the amount of extra memory used due to fixed
		 * loading.
		 */
		if (load_type == TOP_LOAD) {
			unsigned long max_addr, space_used;
			/*
			 * ------------ max_addr
			 * | /wasted/ |                 | offset
			 * |..........|..............................
			 * |  image   |                 | image_flen
			 * |----------| fixed_addr
			 * |          |
			 * |          |
			 * ------------ total_base
			 */
			max_addr = mem_layout->total_base + mem_layout->total_size;
			/*
			 * Compute the amount of memory used by the image.
			 * Corresponds to all space above the image load
			 * address.
			 */
			space_used = max_addr - fixed_addr;
			/*
			 * Calculate the amount of wasted memory within the
			 * amount of memory used by the image.
			 */
			offset = space_used - image_size;
		} else /* BOT_LOAD */
			/*
			 * ------------
			 * |          |
			 * |          |
			 * |----------|
			 * |  image   |
			 * |..........| fixed_addr
			 * | /wasted/ |                 | offset
			 * ------------ total_base
			 */
			offset = fixed_addr - mem_layout->total_base;
	}

	/* We have enough space so load the image now */
	/* TODO: Consider whether to try to recover/retry a partially successful read */
	io_result = io_read(image_handle, image_base, image_size, &bytes_read);
	if ((io_result != IO_SUCCESS) || (bytes_read < image_size)) {
		WARN("Failed to load '%s' file (%i)\n", image_name, io_result);
		goto exit;
	}

	image_data->image_base = image_base;
	image_data->image_size = image_size;

	entry_point_info->pc = image_base;

	/*
	 * File has been successfully loaded. Update the free memory
	 * data structure & flush the contents of the TZRAM so that
	 * the next EL can see it.
	 */
	/* Update the memory contents */
	flush_dcache_range(image_base, image_size);

	mem_layout->free_size -= image_size + offset;

	/* Update the base of free memory since its moved up */
	if (load_type == BOT_LOAD)
		mem_layout->free_base += offset + image_size;

exit:
	io_close(image_handle);
	/* Ignore improbable/unrecoverable error in 'close' */

	/* TODO: Consider maintaining open device connection from this bootloader stage */
	io_dev_close(dev_handle);
	/* Ignore improbable/unrecoverable error in 'dev_close' */

	return io_result;
}
Example #2
0
static struct io_plan read_done(struct io_conn *conn, struct data *d)
{
	ok1(d->state == 2 || d->state == 3);
	d->state++;
	return io_close();
}
Example #3
0
int main(int argc, const char **argv) // ignore_convention
{
    dbg_logger_stdout();
    char aPath[256] = {0};
    char aPathEscaped[512] = {0};
    str_copy(aPath, argv[0], sizeof(aPath));
    char *pBackSlash = (char *)str_find_rev(aPath, "\\");
    if (pBackSlash)
        pBackSlash[0] = 0;

    int x = 0;
    for (int i = 0; i < str_length(aPath); i++)
    {
        aPathEscaped[x++] = aPath[i];
        if (aPath[i] == '\\')
            aPathEscaped[x++] = aPath[i];
    }

    dbg_msg("argv0", argv[0]);
    dbg_msg("aPath", aPath);
    dbg_msg("ePath", aPathEscaped);


    dbg_msg("", "Generating registry information");

    IOHANDLE File = io_open("tw.reg", IOFLAG_WRITE);

    io_write(File, "Windows Registry Editor Version 5.00\n", str_length("Windows Registry Editor Version 5.00\n"));

    io_write(File, "[HKEY_CLASSES_ROOT\\tw]\n", str_length("[HKEY_CLASSES_ROOT\\tw]\n"));

    io_write(File, "\"URL Protocol\"=\"\"\n", str_length("\"URL Protocol\"=\"\"\n"));

    io_write(File, "@=\"URL:Teeworlds Protocol\"\n", str_length("@=\"URL:Teeworlds Protocol\"\n"));

    io_write(File, "[HKEY_CLASSES_ROOT\\tw\\DefaultIcon]\n", str_length("[HKEY_CLASSES_ROOT\\tw\\DefaultIcon]\n"));

    io_write(File, "@=\"", str_length("@=\""));
    io_write(File, aPathEscaped, str_length(aPathEscaped));
    io_write(File, "n-client.exe", str_length("n-client.exe"));
    io_write(File, "\"\n", str_length("\"\n"));

    io_write(File, "[HKEY_CLASSES_ROOT\\tw\\shell]\n", str_length("[HKEY_CLASSES_ROOT\\tw\\shell]\n"));

    io_write(File, "@=\"open\"\n", str_length("@=\"open\"\n"));

    io_write(File, "[HKEY_CLASSES_ROOT\\tw\\shell\\open]\n", str_length("[HKEY_CLASSES_ROOT\\tw\\shell\\open]\n"));

    io_write(File, "[HKEY_CLASSES_ROOT\\tw\\shell\\open\\command]\n", str_length("[HKEY_CLASSES_ROOT\\tw\\shell\\open\\command]\n"));

    io_write(File, "@=\"", str_length("@=\""));
    io_write(File, aPathEscaped, str_length(aPathEscaped));
    io_write(File, "tw_proto_start.bat %1\"\n", str_length("tw_proto_start.bat %1\"\n"));

    io_close(File);

    dbg_msg("", "Registering protocol");
    int i = system("tw.reg");
    if (i)
        dbg_msg("", "Errorcode: %i");
    dbg_msg("", "Cleaning up");
    fs_remove("tw.reg");

    return 0;
}
Example #4
0
/* Open a file for access from package. */
static int fip_file_open(io_dev_info_t *dev_info, const uintptr_t spec,
			 io_entity_t *entity)
{
	int result;
	uintptr_t backend_handle;
	const io_uuid_spec_t *uuid_spec = (io_uuid_spec_t *)spec;
	size_t bytes_read;
	int found_file = 0;

	assert(uuid_spec != NULL);
	assert(entity != NULL);

	/* Can only have one file open at a time for the moment. We need to
	 * track state like file cursor position. We know the header lives at
	 * offset zero, so this entry should never be zero for an active file.
	 * When the system supports dynamic memory allocation we can allow more
	 * than one open file at a time if needed.
	 */
	if (current_file.entry.offset_address != 0) {
		WARN("fip_file_open : Only one open file at a time.\n");
		return -ENOMEM;
	}

	/* Attempt to access the FIP image */
	result = io_open(backend_dev_handle, backend_image_spec,
			 &backend_handle);
	if (result != 0) {
		WARN("Failed to open Firmware Image Package (%i)\n", result);
		result = -ENOENT;
		goto fip_file_open_exit;
	}

	/* Seek past the FIP header into the Table of Contents */
	result = io_seek(backend_handle, IO_SEEK_SET, sizeof(fip_toc_header_t));
	if (result != 0) {
		WARN("fip_file_open: failed to seek\n");
		result = -ENOENT;
		goto fip_file_open_close;
	}

	found_file = 0;
	do {
		result = io_read(backend_handle,
				 (uintptr_t)&current_file.entry,
				 sizeof(current_file.entry),
				 &bytes_read);
		if (result == 0) {
			if (compare_uuids(&current_file.entry.uuid,
					  &uuid_spec->uuid) == 0) {
				found_file = 1;
				break;
			}
		} else {
			WARN("Failed to read FIP (%i)\n", result);
			goto fip_file_open_close;
		}
	} while (compare_uuids(&current_file.entry.uuid, &uuid_null) != 0);

	if (found_file == 1) {
		/* All fine. Update entity info with file state and return. Set
		 * the file position to 0. The 'current_file.entry' holds the
		 * base and size of the file.
		 */
		current_file.file_pos = 0;
		entity->info = (uintptr_t)&current_file;
	} else {
		/* Did not find the file in the FIP. */
		current_file.entry.offset_address = 0;
		result = -ENOENT;
	}

 fip_file_open_close:
	io_close(backend_handle);

 fip_file_open_exit:
	return result;
}
Example #5
0
int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser)
{
	int l = str_length(pName);
	if(l < 5 || IsDir || str_comp(pName+l-5, ".json") != 0)
		return 0;

	CSkins *pSelf = (CSkins *)pUser;

	// read file data into buffer
	char aBuf[512];
	str_format(aBuf, sizeof(aBuf), "skins/%s", pName);
	IOHANDLE File = pSelf->Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL);
	if(!File)
		return 0;
	int FileSize = (int)io_length(File);
	char *pFileData = (char *)mem_alloc(FileSize, 1);
	io_read(File, pFileData, FileSize);
	io_close(File);

	// init
	CSkin Skin = pSelf->m_DummySkin;
	str_copy(Skin.m_aName, pName, min((int)sizeof(Skin.m_aName),l-4));
	if(pSelf->Find(Skin.m_aName, true) != -1)
		return 0;
	bool SpecialSkin = pName[0] == 'x' && pName[1] == '_';

	// parse json data
	json_settings JsonSettings;
	mem_zero(&JsonSettings, sizeof(JsonSettings));
	char aError[256];
	json_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, FileSize, aError);
	mem_free(pFileData);

	if(pJsonData == 0)
	{
		pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, aBuf, aError);
		return 0;
	}

	// extract data
	const json_value &rStart = (*pJsonData)["skin"];
	if(rStart.type == json_object)
	{
		for(int PartIndex = 0; PartIndex < NUM_SKINPARTS; ++PartIndex)
		{
			const json_value &rPart = rStart[(const char *)ms_apSkinPartNames[PartIndex]];
			if(rPart.type != json_object)
				continue;

			// filename
			const json_value &rFilename = rPart["filename"];
			if(rFilename.type == json_string)
			{
				int SkinPart = pSelf->FindSkinPart(PartIndex, (const char *)rFilename, SpecialSkin);
				if(SkinPart > -1)
					Skin.m_apParts[PartIndex] = pSelf->GetSkinPart(PartIndex, SkinPart);
			}

			// use custom colors
			bool UseCustomColors = false;
			const json_value &rColour = rPart["custom_colors"];
			if(rColour.type == json_string)
			{
				UseCustomColors = str_comp((const char *)rColour, "true") == 0;
			}
			Skin.m_aUseCustomColors[PartIndex] = UseCustomColors;

			// color components
			if(!UseCustomColors)
				continue;

			for(int i = 0; i < NUM_COLOR_COMPONENTS; i++)
			{
				if(PartIndex != SKINPART_MARKING && i == 3)
					continue;

				const json_value &rComponent = rPart[(const char *)ms_apColorComponents[i]];
				if(rComponent.type == json_integer)
				{
					switch(i)
					{
					case 0: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFF00FFFF) | (rComponent.u.integer << 16); break;
					case 1:	Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFFFF00FF) | (rComponent.u.integer << 8); break;
					case 2: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFFFFFF00) | rComponent.u.integer; break;
					case 3: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0x00FFFFFF) | (rComponent.u.integer << 24); break;
					}
				}
			}
		}
	}

	// clean up
	json_value_free(pJsonData);

	// set skin data
	Skin.m_Flags = SpecialSkin ? SKINFLAG_SPECIAL : 0;
	if(DirType != IStorage::TYPE_SAVE)
		Skin.m_Flags |= SKINFLAG_STANDARD;
	if(g_Config.m_Debug)
	{
		str_format(aBuf, sizeof(aBuf), "load skin %s", Skin.m_aName);
		pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "skins", aBuf);
	}
	pSelf->m_aSkins.add(Skin);

	return 0;
}
Example #6
0
int mainLoop (char *confpath) {
	cfg_t *cfg;
	redisContext *c;
	redisReply *reply;
	char *respcpy, *ascval, *curtok;
	unsigned int chan, val, start;
	int iofd, retval=-1, maxchain, numchan;
	int outbpc[3];
	/* Localize messages & types according to environment, since v2.9 */
	setlocale(LC_MESSAGES, "");
	setlocale(LC_CTYPE, "");

	/* Read configuration and initialize to default state*/
	statestr=malloc(sizeof(DEFSTATE)+1);
	strcpy(statestr,DEFSTATE);

	cfg = parse_conf(confpath == NULL ? "/etc/bone-shiftreg.conf" : confpath);
	if (!cfg) {
		fprintf(stderr,"Error parsing configuration file!\n");
		retval=-2;
		goto cleanupnone;
	}
	outbpc[0] = cfg_getint(cfg,"ser0-num-channels");
	outbpc[1] = cfg_getint(cfg,"ser1-num-channels");
	outbpc[2] = cfg_getint(cfg,"ser2-num-channels");
	if(cfg_getbool(cfg,"debug")){
		debug = 1;
	} else {
		debug = 0;
	}
	start = cfg_getint(cfg,"start-address");
	numchan = summation(0,NUMPINS-1, outbpc);
	printf("This board has a total of %d channels\n", numchan);

	/* Open remoteproc device */
	if((iofd = io_init(cfg_getstr(cfg,"pru-remoteproc-file"))) < 0){
		fprintf(stderr,"Failed to open remoteproc device file! Firmware still booting?\n");
		retval = -1;
		goto cleanupconf;
	}
	/* Set output channel count */
	maxchain = imax(imax(outbpc[0],outbpc[1]),outbpc[2]);
	if(maxchain == 0){
		fprintf(stderr,"At least one output chain must have more then zero channels!\n");
		goto cleanupio;
	}

	if(io_set_nchannels(iofd, maxchain) < 0){
		fprintf(stderr,"Failed to set max chain length to %d!\n", maxchain);
		retval = -2;
		goto cleanupio;
	}
	/* Establish Redis connection */
	printf("Connecting to redis at %s, port %ld\n", cfg_getstr(cfg,"redis-host"), cfg_getint(cfg,"redis-port"));
	c = redisConnect(cfg_getstr(cfg,"redis-host"), cfg_getint(cfg,"redis-port"));
	/* Handle Redis connection errors */
	if (c == NULL || c->err) {
		if (c) {
			fprintf(stderr,"Error: %s\n", c->errstr);
			goto cleanupall;
		} else {
			fprintf(stderr,"Can't allocate redis context\n");
			goto cleanupio;
		}
	}
	/* Authenticate if needed */
	if(cfg_getbool(cfg,"redis-authrequired")){
		const char authpref[] = "AUTH ";
		char *authstr = malloc(sizeof(authpref) + strlen(cfg_getstr(cfg,"redis-password")) + 1);
		memcpy(authstr, authpref, sizeof(authpref));
		strcat(authstr, cfg_getstr(cfg,"redis-password"));
		reply = redisCommand(c, authstr);
		free(authstr);
		if(!reply || reply->type == REDIS_REPLY_ERROR){
			fprintf(stderr,"authentication failed\n");
			goto cleanupall;
		}
		if(reply)
			freeReplyObject(reply);
	}
	reply = redisCommand(c, "PING");
	if(!reply || reply->type == REDIS_REPLY_ERROR){
		fprintf(stderr,"Unable to execute Redis commands, are you authenticated if necessary?\n");
		if(reply)
			freeReplyObject(reply);
		goto cleanupall;
	} else { 
		freeReplyObject(reply);
	}
	/* If we have gotten here we have initialized successfully */
	/* Restore state */ 
	if(cfg_getbool(cfg,"persistent-state")){
		if(restoreState(c, iofd, start, start+numchan, outbpc, NUMPINS) == -2){
			retval = -2;
			goto cleanupall;
		}
	}
	retval=0;
	/* Message handling loop */
	if(debug)
		fprintf(stderr,"Subscribed...\n");
	reply = redisCommand(c, "SUBSCRIBE changes");
	freeReplyObject(reply);
	while(redisGetReply(c,(void *)&reply) == REDIS_OK) {
		if(debug)
			fprintf(stderr,"Begin message parsing\n");
		// consume message
		if (reply == NULL) 
			continue;
		if (reply->type == REDIS_REPLY_ARRAY) {
			if(reply->elements == 3) {
				if(reply->element[0]->type == REDIS_REPLY_STRING && reply->element[2]->type == REDIS_REPLY_STRING && strcmp("message", reply->element[0]->str) == 0){
					if(debug)  
						fprintf(stderr,"Processing incoming message %s\n", reply->element[2]->str);
					//Message parsing
					respcpy = malloc(strlen(reply->element[2]->str)+1);
					assert(respcpy != NULL);
					strcpy(respcpy, reply->element[2]->str);
					#ifdef ALLOWSHUTDOWN
					if(strstr(respcpy, "@")){
						free(respcpy);
						freeReplyObject(reply);
						retval = -3;
						goto cleanupall;
					}
					#endif
					if(strstr(respcpy, "!")){
						//Reload requested, cleanup and return 0 (which causes a reload)
						free(respcpy);
						freeReplyObject(reply);
						goto cleanupall;
					}
					curtok = strtok(respcpy,",");
					while(curtok != NULL){
						ascval = strsep(&curtok, ":");
						if(curtok != NULL){
							chan = atoi(ascval);
							val = atoi(curtok);
							//Does this channel belong to us? If so, update!
							if(setChannelIfOurs(iofd, chan, val, start, outbpc, NUMPINS) == -2){
								/* IO error, bail out! */
								fprintf(stderr, "IO error, bailing!\n");
								freeReplyObject(reply);
								free(respcpy);
								goto cleanupall;
							}
						} else {
							fprintf(stderr, "Malformed message published to channel!\n");
						}
						curtok = strtok(NULL,",");
					}
					free(respcpy);
				}
			} else {
				fprintf(stderr, "Invalid number of elements in reply array!\n");
			}
		}
		freeReplyObject(reply);
	}
	fprintf(stderr, "Lost connection to redis server!\n");
cleanupall:
	redisFree(c);
cleanupio:
	io_close(iofd);
cleanupconf:
	cfg_free(cfg);
cleanupnone:
	free(statestr);
	return retval;
}
Example #7
0
static struct io_plan *writer(struct io_conn *conn, struct write_state *ws)
{
	if (ws->count++ == num_writes)
		return io_close(conn);
	return io_write(conn, &ws->id, 1, writer, ws);
}
Example #8
0
void CMapLayers::OnRender()
{
	if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)
		return;

	CUIRect Screen;
	Graphics()->GetScreen(&Screen.x, &Screen.y, &Screen.w, &Screen.h);

	vec2 Center = m_pClient->m_pCamera->m_Center;
	//float center_x = gameclient.camera->center.x;
	//float center_y = gameclient.camera->center.y;

	bool PassedGameLayer = false;

	for(int g = 0; g < m_pLayers->NumGroups(); g++)
	{
		CMapItemGroup *pGroup = m_pLayers->GetGroup(g);

		if(!pGroup)
		{
			dbg_msg("MapLayers", "Error:Group was null, Group Number = %d, Total Groups = %d", g, m_pLayers->NumGroups());
			dbg_msg("MapLayers", "This is here to prevent a crash but the source of this is unknown, please report this for it to get fixed");
			dbg_msg("MapLayers", "we need mapname and crc and the map that caused this if possible, and anymore info you think is relevant");
			continue;
		}

		if(!g_Config.m_GfxNoclip && pGroup->m_Version >= 2 && pGroup->m_UseClipping)
		{
			// set clipping
			float Points[4];
			MapScreenToGroup(Center.x, Center.y, m_pLayers->GameGroup(), m_pClient->m_pCamera->m_Zoom);
			Graphics()->GetScreen(&Points[0], &Points[1], &Points[2], &Points[3]);
			float x0 = (pGroup->m_ClipX - Points[0]) / (Points[2]-Points[0]);
			float y0 = (pGroup->m_ClipY - Points[1]) / (Points[3]-Points[1]);
			float x1 = ((pGroup->m_ClipX+pGroup->m_ClipW) - Points[0]) / (Points[2]-Points[0]);
			float y1 = ((pGroup->m_ClipY+pGroup->m_ClipH) - Points[1]) / (Points[3]-Points[1]);

			Graphics()->ClipEnable((int)(x0*Graphics()->ScreenWidth()), (int)(y0*Graphics()->ScreenHeight()),
				(int)((x1-x0)*Graphics()->ScreenWidth()), (int)((y1-y0)*Graphics()->ScreenHeight()));
		}

		if(!g_Config.m_ClZoomBackgroundLayers && !pGroup->m_ParallaxX && !pGroup->m_ParallaxY)
			MapScreenToGroup(Center.x, Center.y, pGroup, 1.0);
		else
			MapScreenToGroup(Center.x, Center.y, pGroup, m_pClient->m_pCamera->m_Zoom);

		for(int l = 0; l < pGroup->m_NumLayers; l++)
		{
			CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer+l);
			bool Render = false;
			bool IsGameLayer = false;
			bool IsFrontLayer = false;
			bool IsSwitchLayer = false;
			bool IsTeleLayer = false;
			bool IsSpeedupLayer = false;
			bool IsTuneLayer = false;

			if(pLayer == (CMapItemLayer*)m_pLayers->GameLayer())
			{
				IsGameLayer = true;
				PassedGameLayer = 1;
			}

			if(pLayer == (CMapItemLayer*)m_pLayers->FrontLayer())
				IsFrontLayer = true;

			if(pLayer == (CMapItemLayer*)m_pLayers->SwitchLayer())
				IsSwitchLayer = true;

			if(pLayer == (CMapItemLayer*)m_pLayers->TeleLayer())
				IsTeleLayer = true;

			if(pLayer == (CMapItemLayer*)m_pLayers->SpeedupLayer())
				IsSpeedupLayer = true;

			if(pLayer == (CMapItemLayer*)m_pLayers->TuneLayer())
				IsTuneLayer = true;

			// skip rendering if detail layers if not wanted
			if(pLayer->m_Flags&LAYERFLAG_DETAIL && !g_Config.m_GfxHighDetail && !IsGameLayer)
				continue;

			if(m_Type == -1)
				Render = true;
			else if(m_Type == 0)
			{
				if(PassedGameLayer)
					return;
				Render = true;
			}
			else
			{
				if(PassedGameLayer && !IsGameLayer)
					Render = true;
			}

			if(Render && pLayer->m_Type == LAYERTYPE_TILES && Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown(KEY_KP0))
			{
				CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer;
				CTile *pTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Data);
				CServerInfo CurrentServerInfo;
				Client()->GetServerInfo(&CurrentServerInfo);
				char aFilename[256];
				str_format(aFilename, sizeof(aFilename), "dumps/tilelayer_dump_%s-%d-%d-%dx%d.txt", CurrentServerInfo.m_aMap, g, l, pTMap->m_Width, pTMap->m_Height);
				IOHANDLE File = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE);
				if(File)
				{
					for(int y = 0; y < pTMap->m_Height; y++)
					{
						for(int x = 0; x < pTMap->m_Width; x++)
							io_write(File, &(pTiles[y*pTMap->m_Width + x].m_Index), sizeof(pTiles[y*pTMap->m_Width + x].m_Index));
						io_write_newline(File);
					}
					io_close(File);
				}
			}

			if((Render && g_Config.m_ClOverlayEntities < 100 && !IsGameLayer && !IsFrontLayer && !IsSwitchLayer && !IsTeleLayer && !IsSpeedupLayer && !IsTuneLayer) || (g_Config.m_ClOverlayEntities && IsGameLayer))
			{
				//layershot_begin();

				if(pLayer->m_Type == LAYERTYPE_TILES)
				{
					CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer;
					if(pTMap->m_Image == -1)
					{
						if(!IsGameLayer)
							Graphics()->TextureSet(-1);
						else
							Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities());
					}
					else
						Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pTMap->m_Image));

					CTile *pTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Data);
					unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Data);

					if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTile))
					{
						Graphics()->BlendNone();
						vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f);
						if(IsGameLayer && g_Config.m_ClOverlayEntities)
							Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f*g_Config.m_ClOverlayEntities/100.0f);
						if(!IsGameLayer && g_Config.m_ClOverlayEntities)
							Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f*(100-g_Config.m_ClOverlayEntities)/100.0f);
						RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE,
														EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset);
						Graphics()->BlendNormal();
						RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT,
														EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset);
					}
				}
				else if(pLayer->m_Type == LAYERTYPE_QUADS)
				{
					CMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer;
					if(pQLayer->m_Image == -1)
						Graphics()->TextureSet(-1);
					else
						Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pQLayer->m_Image));

					CQuad *pQuads = (CQuad *)m_pLayers->Map()->GetDataSwapped(pQLayer->m_Data);

					Graphics()->BlendNone();
					RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this);
					Graphics()->BlendNormal();
					RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this);
				}

				//layershot_end();
			}
			else if(g_Config.m_ClOverlayEntities && IsFrontLayer)
			{
				CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer;
				Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities());

				CTile *pFrontTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Front);
				unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Front);

				if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTile))
				{
					Graphics()->BlendNone();
					vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f);
					if(g_Config.m_ClOverlayEntities)
						Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f*g_Config.m_ClOverlayEntities/100.0f);
					RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE,
							EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset);
					Graphics()->BlendNormal();
					RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT,
							EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset);
				}
			}
			else if(g_Config.m_ClOverlayEntities && IsSwitchLayer)
			{
				CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer;
				Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities());

				CSwitchTile *pSwitchTiles = (CSwitchTile *)m_pLayers->Map()->GetData(pTMap->m_Switch);
				unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Switch);

				if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CSwitchTile))
				{
					Graphics()->BlendNone();
					vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f);
					if(g_Config.m_ClOverlayEntities)
						Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f*g_Config.m_ClOverlayEntities/100.0f);
					RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE);
					Graphics()->BlendNormal();
					RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT);
					RenderTools()->RenderSwitchOverlay(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, g_Config.m_ClOverlayEntities/100.0f);
				}
			}
			else if(g_Config.m_ClOverlayEntities && IsTeleLayer)
			{
				CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer;
				Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities());

				CTeleTile *pTeleTiles = (CTeleTile *)m_pLayers->Map()->GetData(pTMap->m_Tele);
				unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Tele);

				if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTeleTile))
				{
					Graphics()->BlendNone();
					vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f);
					if(g_Config.m_ClOverlayEntities)
						Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f*g_Config.m_ClOverlayEntities/100.0f);
					RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE);
					Graphics()->BlendNormal();
					RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT);
					RenderTools()->RenderTeleOverlay(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, g_Config.m_ClOverlayEntities/100.0f);
				}
			}
			else if(g_Config.m_ClOverlayEntities && IsSpeedupLayer)
			{
				CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer;
				Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities());

				CSpeedupTile *pSpeedupTiles = (CSpeedupTile *)m_pLayers->Map()->GetData(pTMap->m_Speedup);
				unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Speedup);

				if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CSpeedupTile))
				{
					Graphics()->BlendNone();
					vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f);
					if(g_Config.m_ClOverlayEntities)
						Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f*g_Config.m_ClOverlayEntities/100.0f);
					RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE);
					Graphics()->BlendNormal();
					RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT);
					RenderTools()->RenderSpeedupOverlay(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, g_Config.m_ClOverlayEntities/100.0f);
				}
			}
			else if(g_Config.m_ClOverlayEntities && IsTuneLayer)
			{
				CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer;
				Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities());

				CTuneTile *pTuneTiles = (CTuneTile *)m_pLayers->Map()->GetData(pTMap->m_Tune);
				unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Tune);

				if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTuneTile))
				{
					Graphics()->BlendNone();
					vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f);
					if(g_Config.m_ClOverlayEntities)
						Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f*g_Config.m_ClOverlayEntities/100.0f);
					RenderTools()->RenderTunemap(pTuneTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE);
					Graphics()->BlendNormal();
					RenderTools()->RenderTunemap(pTuneTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT);
					//RenderTools()->RenderTuneOverlay(pTuneTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, g_Config.m_ClOverlayEntities/100.0f);
				}
			}
		}
		if(!g_Config.m_GfxNoclip)
			Graphics()->ClipDisable();
	}

	if(!g_Config.m_GfxNoclip)
		Graphics()->ClipDisable();

	// reset the screen like it was before
	Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);
}
void engine_close(engine_t * engine) {

   ASSERT(engine_is_ok(engine));

   io_close(engine->io);
}
Example #10
0
int CMain::ReadConfig()
{
	// read and parse config
	IOHANDLE File = io_open(m_Config.m_aConfigFile, IOFLAG_READ);
	if(!File)
	{
		dbg_msg("main", "Couldn't open %s", m_Config.m_aConfigFile);
		return 1;
	}
	int FileSize = (int)io_length(File);
	char *pFileData = (char *)mem_alloc(FileSize + 1, 1);

	io_read(File, pFileData, FileSize);
	pFileData[FileSize] = 0;
	io_close(File);

	// parse json data
	json_settings JsonSettings;
	mem_zero(&JsonSettings, sizeof(JsonSettings));
	char aError[256];
	json_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, strlen(pFileData), aError);
	if(!pJsonData)
	{
		dbg_msg("main", "JSON Error in file %s: %s", m_Config.m_aConfigFile, aError);
		mem_free(pFileData);
		return 1;
	}

	// reset clients
	for(int i = 0; i < NET_MAX_CLIENTS; i++)
	{
		if(!Client(i)->m_Active || !Client(i)->m_Connected)
			continue;

		m_Server.Network()->Drop(Client(i)->m_ClientNetID, "Server reloading...");
	}
	mem_zero(m_aClients, sizeof(m_aClients));
	for(int i = 0; i < NET_MAX_CLIENTS; i++)
		m_aClients[i].m_ClientNetID = -1;

	// extract data
	int ID = 0;
	const json_value &rStart = (*pJsonData)["servers"];
	if(rStart.type == json_array)
	{
		for(unsigned i = 0; i < rStart.u.array.length; i++)
		{
			if(ID < 0 || ID >= NET_MAX_CLIENTS)
				continue;

			Client(ID)->m_Active = true;
			Client(ID)->m_Disabled = rStart[i]["disabled"].u.boolean;
			str_copy(Client(ID)->m_aName, rStart[i]["name"].u.string.ptr, sizeof(Client(ID)->m_aName));
			str_copy(Client(ID)->m_aUsername, rStart[i]["username"].u.string.ptr, sizeof(Client(ID)->m_aUsername));
			str_copy(Client(ID)->m_aType, rStart[i]["type"].u.string.ptr, sizeof(Client(ID)->m_aType));
			str_copy(Client(ID)->m_aHost, rStart[i]["host"].u.string.ptr, sizeof(Client(ID)->m_aHost));
			str_copy(Client(ID)->m_aLocation, rStart[i]["location"].u.string.ptr, sizeof(Client(ID)->m_aLocation));
			str_copy(Client(ID)->m_aPassword, rStart[i]["password"].u.string.ptr, sizeof(Client(ID)->m_aPassword));

			if(m_Config.m_Verbose)
			{
				if(Client(ID)->m_Disabled)
					dbg_msg("main", "[#%d: Name: \"%s\", Username: \"%s\", Type: \"%s\", Host: \"%s\", Location: \"%s\", Password: \"%s\"]",
						ID, Client(ID)->m_aName, Client(ID)->m_aUsername, Client(ID)->m_aType, Client(ID)->m_aHost, Client(ID)->m_aLocation, Client(ID)->m_aPassword);
				else
					dbg_msg("main", "#%d: Name: \"%s\", Username: \"%s\", Type: \"%s\", Host: \"%s\", Location: \"%s\", Password: \"%s\"",
						ID, Client(ID)->m_aName, Client(ID)->m_aUsername, Client(ID)->m_aType, Client(ID)->m_aHost, Client(ID)->m_aLocation, Client(ID)->m_aPassword);

			}
			ID++;
		}
	}

	// clean up
	json_value_free(pJsonData);
	mem_free(pFileData);

	// tell clients to reload the page
	m_JSONUpdateThreadData.m_ReloadRequired = 2;

	return 0;
}
static struct io_plan wake_it(struct io_conn *conn, struct io_conn *reader)
{
	io_wake(reader, io_read(inbuf, 8, io_close_cb, NULL));
	return io_close();
}
Example #12
0
void CMain::JSONUpdateThread(void *pUser)
{
	CJSONUpdateThreadData *m_pJSONUpdateThreadData = (CJSONUpdateThreadData *)pUser;
	CClient *pClients = m_pJSONUpdateThreadData->pClients;
	CConfig *pConfig = m_pJSONUpdateThreadData->pConfig;

	while(gs_Running)
	{
		char aFileBuf[2048*NET_MAX_CLIENTS];
		char *pBuf = aFileBuf;

		str_format(pBuf, sizeof(aFileBuf), "{\n\"servers\": [\n");
		pBuf += strlen(pBuf);

		for(int i = 0; i < NET_MAX_CLIENTS; i++)
		{
			if(!pClients[i].m_Active || pClients[i].m_Disabled)
				continue;

			if(pClients[i].m_Connected)
			{
				// Connectivity
				bool Online4;
				bool Online6;
				Online4 = pClients[i].m_Stats.m_Online4;
				Online6 = pClients[i].m_Stats.m_Online6;

				// Uptime
				char aUptime[16];
				int Days = pClients[i].m_Stats.m_Uptime/60.0/60.0/24.0;
				if(Days > 0)
				{
					if(Days > 1)
						str_format(aUptime, sizeof(aUptime), "%d days", Days);
					else
						str_format(aUptime, sizeof(aUptime), "%d day", Days);
				}
				else
					str_format(aUptime, sizeof(aUptime), "%02d:%02d:%02d", (int)(pClients[i].m_Stats.m_Uptime/60.0/60.0), (int)((pClients[i].m_Stats.m_Uptime/60)%60), (int)((pClients[i].m_Stats.m_Uptime)%60));

				// Load
				float Load = pClients[i].m_Stats.m_Load;

				// CPU
				int CPU = pClients[i].m_Stats.m_CPU;

				// Memory
				int Memory;
				if(pClients[i].m_Stats.m_MemTotal)
					Memory = round(((float)pClients[i].m_Stats.m_MemUsed/pClients[i].m_Stats.m_MemTotal)*100.0);
				else
					Memory = 0;

				// HDD
				int HDD;
				if(pClients[i].m_Stats.m_HDDTotal)
					HDD = round(((float)pClients[i].m_Stats.m_HDDUsed/pClients[i].m_Stats.m_HDDTotal)*100.0);
				else
					HDD = 0;

				str_format(pBuf, sizeof(aFileBuf) - (pBuf - aFileBuf), "{ \"name\": \"%s\", \"type\": \"%s\", \"host\": \"%s\", \"location\": \"%s\", \"online4\": %s, \"online6\": %s, \"uptime\": \"%s\", \"load\": \"%.2f\", \"network_rx\": %d, \"network_tx\": %d, \"cpu\": %d, \"memory\": %d, \"memory_total\": %" PRId64 ", \"memory_used\": %" PRId64 ", \"hdd\": %d, \"hdd_total\": %" PRId64 ", \"hdd_used\": %" PRId64 " },\n",
					pClients[i].m_aName, pClients[i].m_aType, pClients[i].m_aHost, pClients[i].m_aLocation, Online4 ? "true" : "false", Online6 ? "true" : "false", aUptime, Load, pClients[i].m_Stats.m_NetworkRx, pClients[i].m_Stats.m_NetworkTx, CPU, Memory, pClients[i].m_Stats.m_MemTotal, pClients[i].m_Stats.m_MemUsed, HDD, pClients[i].m_Stats.m_HDDTotal, pClients[i].m_Stats.m_HDDUsed);
				pBuf += strlen(pBuf);
			}
			else
			{
				str_format(pBuf, sizeof(aFileBuf) - (pBuf - aFileBuf), "{ \"name\": \"%s\", \"type\": \"%s\", \"host\": \"%s\", \"location\": \"%s\", \"online4\": false, \"online6\": false },\n",
					pClients[i].m_aName, pClients[i].m_aType, pClients[i].m_aHost, pClients[i].m_aLocation);
				pBuf += strlen(pBuf);
			}
		}
		if(!m_pJSONUpdateThreadData->m_ReloadRequired)
			str_format(pBuf - 2, sizeof(aFileBuf) - (pBuf - aFileBuf), "\n],\n\"updated\": \"%lld\"\n}", (long long)time(/*ago*/0));
		else
		{
			str_format(pBuf - 2, sizeof(aFileBuf) - (pBuf - aFileBuf), "\n],\n\"updated\": \"%lld\",\n\"reload\": true\n}", (long long)time(/*ago*/0));
			m_pJSONUpdateThreadData->m_ReloadRequired--;
		}
		pBuf += strlen(pBuf);

		char aJSONFileTmp[1024];
		str_format(aJSONFileTmp, sizeof(aJSONFileTmp), "%s~", pConfig->m_aJSONFile);
		IOHANDLE File = io_open(aJSONFileTmp, IOFLAG_WRITE);
		if(!File)
		{
			dbg_msg("main", "Couldn't open %s", aJSONFileTmp);
			exit(1);
		}
		io_write(File, aFileBuf, (pBuf - aFileBuf));
		io_flush(File);
		io_close(File);
		fs_rename(aJSONFileTmp, pConfig->m_aJSONFile);
		thread_sleep(1000);
	}
	fs_remove(pConfig->m_aJSONFile);
}
Example #13
0
int close_h_file(               // CLOSE H FILE
    void )
{
    return( io_close( h_file ) );
}
Example #14
0
int close_c_file(               // CLOSE C FILE
    void )
{
    return( io_close( c_file ) );
}
Example #15
0
int SC_exec_commands(const char *shell, char **cmnds, char **env, int to,
		     const char *lname, const char *fname, int na, int show,
		     int ignore, int dmp)
   {int i, n, st, sto;
    conpool *cpo;
    fspec *filter;
    asyncstate *cs;
    SC_thread_proc *ps;

    ps = _SC_get_thr_processes(-1);

    GET_CLIENT_STATE(cs);

/* filter junk messages out of response */
    filter = _SC_read_filter(fname);

    cpo = cs->pool;
    sto = cs->to_stdout;

    _SC_setup_async_state(cs, 0);

    if (lname != NULL)
       {cs->log = io_open(lname, "a");
	SC_setbuf(cs->log, NULL);}
    else
       cs->log = NULL;

    SC_ptr_arr_len(n, cmnds);

    ps->ed.n      = n;
    ps->ed.to     = to;
    ps->ed.na     = na;
    ps->ed.show   = show;
    ps->ed.dmp    = dmp;
    ps->ed.ignore = ignore;
    ps->ed.cmnds  = cmnds;
    ps->ed.shell  = shell;
    ps->ed.env    = env;
    ps->ed.filter = filter;
    ps->ed.res    = CMAKE_N(int, n);
    for (i = 0; i < n; i++)
        ps->ed.res[i] = 0;

/* run each command until it succeeds or definitively fails
 * try to avoid failing on system fault type errors
 */
    st = 0;
    if (SC_n_threads > 1)
       {SC_do_tasks((PFInt) _SC_exec_one, &ps->ed, n, 0, TRUE);
	for (i = 0; i < n; i++)
	    st |= ps->ed.res[i];}
    else
       {int it[2];
	void *a;

	a     = &ps->ed;
	it[0] = 0;
	it[1] = n;
	st = _SC_exec_one(&a, it);
	for (i = 0; i < n; i++)
	    st |= ps->ed.res[i];};

    if (lname != NULL)
       io_close(cs->log);

    cs->pool      = cpo;
    cs->to_stdout = sto;

    _SC_free_filter(filter);
    CFREE(ps->ed.res);

    return(st);}
Example #16
0
bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int StorageType)
{
	dbg_msg("datafile", "loading. filename='%s'", pFilename);

	IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType);
	if(!File)
	{
		dbg_msg("datafile", "could not open '%s'", pFilename);
		return false;
	}


	// take the CRC of the file and store it
	unsigned Crc = 0;
	{
		enum
		{
			BUFFER_SIZE = 64*1024
		};

		unsigned char aBuffer[BUFFER_SIZE];

		while(1)
		{
			unsigned Bytes = io_read(File, aBuffer, BUFFER_SIZE);
			if(Bytes <= 0)
				break;
			Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention
		}

		io_seek(File, 0, IOSEEK_START);
	}


	// TODO: change this header
	CDatafileHeader Header;
	io_read(File, &Header, sizeof(Header));
	if(Header.m_aID[0] != 'A' || Header.m_aID[1] != 'T' || Header.m_aID[2] != 'A' || Header.m_aID[3] != 'D')
	{
		if(Header.m_aID[0] != 'D' || Header.m_aID[1] != 'A' || Header.m_aID[2] != 'T' || Header.m_aID[3] != 'A')
		{
			dbg_msg("datafile", "wrong signature. %x %x %x %x", Header.m_aID[0], Header.m_aID[1], Header.m_aID[2], Header.m_aID[3]);
			return 0;
		}
	}

#if defined(CONF_ARCH_ENDIAN_BIG)
	swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int));
#endif
	if(Header.m_Version != 3 && Header.m_Version != 4)
	{
		dbg_msg("datafile", "wrong version. version=%x", Header.m_Version);
		return 0;
	}

	// read in the rest except the data
	unsigned Size = 0;
	Size += Header.m_NumItemTypes*sizeof(CDatafileItemType);
	Size += (Header.m_NumItems+Header.m_NumRawData)*sizeof(int);
	if(Header.m_Version == 4)
		Size += Header.m_NumRawData*sizeof(int); // v4 has uncompressed data sizes aswell
	Size += Header.m_ItemSize;

	unsigned AllocSize = Size;
	AllocSize += sizeof(CDatafile); // add space for info structure
	AllocSize += Header.m_NumRawData*sizeof(void*); // add space for data pointers

	CDatafile *pTmpDataFile = (CDatafile*)mem_alloc(AllocSize, 1);
	pTmpDataFile->m_Header = Header;
	pTmpDataFile->m_DataStartOffset = sizeof(CDatafileHeader) + Size;
	pTmpDataFile->m_ppDataPtrs = (char**)(pTmpDataFile+1);
	pTmpDataFile->m_pData = (char *)(pTmpDataFile+1)+Header.m_NumRawData*sizeof(char *);
	pTmpDataFile->m_File = File;
	pTmpDataFile->m_Crc = Crc;

	// clear the data pointers
	mem_zero(pTmpDataFile->m_ppDataPtrs, Header.m_NumRawData*sizeof(void*));

	// read types, offsets, sizes and item data
	unsigned ReadSize = io_read(File, pTmpDataFile->m_pData, Size);
	if(ReadSize != Size)
	{
		io_close(pTmpDataFile->m_File);
		mem_free(pTmpDataFile);
		pTmpDataFile = 0;
		dbg_msg("datafile", "couldn't load the whole thing, wanted=%d got=%d", Size, ReadSize);
		return false;
	}

	Close();
	m_pDataFile = pTmpDataFile;

#if defined(CONF_ARCH_ENDIAN_BIG)
	swap_endian(m_pDataFile->m_pData, sizeof(int), min(static_cast<unsigned>(Header.m_Swaplen), Size) / sizeof(int));
#endif

	//if(DEBUG)
	{
		dbg_msg("datafile", "allocsize=%d", AllocSize);
		dbg_msg("datafile", "readsize=%d", ReadSize);
		dbg_msg("datafile", "swaplen=%d", Header.m_Swaplen);
		dbg_msg("datafile", "item_size=%d", m_pDataFile->m_Header.m_ItemSize);
	}

	m_pDataFile->m_Info.m_pItemTypes = (CDatafileItemType *)m_pDataFile->m_pData;
	m_pDataFile->m_Info.m_pItemOffsets = (int *)&m_pDataFile->m_Info.m_pItemTypes[m_pDataFile->m_Header.m_NumItemTypes];
	m_pDataFile->m_Info.m_pDataOffsets = (int *)&m_pDataFile->m_Info.m_pItemOffsets[m_pDataFile->m_Header.m_NumItems];
	m_pDataFile->m_Info.m_pDataSizes = (int *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData];

	if(Header.m_Version == 4)
		m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataSizes[m_pDataFile->m_Header.m_NumRawData];
	else
		m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData];
	m_pDataFile->m_Info.m_pDataStart = m_pDataFile->m_Info.m_pItemStart + m_pDataFile->m_Header.m_ItemSize;

	dbg_msg("datafile", "loading done. datafile='%s'", pFilename);

	if(DEBUG)
	{
		/*
		for(int i = 0; i < m_pDataFile->data.num_raw_data; i++)
		{
			void *p = datafile_get_data(df, i);
			dbg_msg("datafile", "%d %d", (int)((char*)p - (char*)(&m_pDataFile->data)), size);
		}

		for(int i = 0; i < datafile_num_items(df); i++)
		{
			int type, id;
			void *data = datafile_get_item(df, i, &type, &id);
			dbg_msg("map", "\t%d: type=%x id=%x p=%p offset=%d", i, type, id, data, m_pDataFile->info.item_offsets[i]);
			int *idata = (int*)data;
			for(int k = 0; k < 3; k++)
				dbg_msg("datafile", "\t\t%d=%d (%x)", k, idata[k], idata[k]);
		}

		for(int i = 0; i < m_pDataFile->data.num_m_aItemTypes; i++)
		{
			dbg_msg("map", "\t%d: type=%x start=%d num=%d", i,
				m_pDataFile->info.m_aItemTypes[i].type,
				m_pDataFile->info.m_aItemTypes[i].start,
				m_pDataFile->info.m_aItemTypes[i].num);
			for(int k = 0; k < m_pDataFile->info.m_aItemTypes[i].num; k++)
			{
				int type, id;
				datafile_get_item(df, m_pDataFile->info.m_aItemTypes[i].start+k, &type, &id);
				if(type != m_pDataFile->info.m_aItemTypes[i].type)
					dbg_msg("map", "\tERROR");
			}
		}
		*/
	}

	return true;
}
Example #17
0
void CGameClient::OnInit()
{
	// set the language
	g_Localization.Load(g_Config.m_ClLanguagefile, Storage(), Console());
	
	// init all components
	for(int i = 0; i < m_All.m_Num; i++)
		m_All.m_paComponents[i]->OnInit();
	
	// setup item sizes
	for(int i = 0; i < NUM_NETOBJTYPES; i++)
		Client()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i));
	
	int64 Start = time_get();
	
	// load default font	
	static CFont *pDefaultFont = 0;
	char aFilename[512];
	IOHANDLE File = Storage()->OpenFile("fonts/DejaVuSans.ttf", IOFLAG_READ, IStorage::TYPE_ALL, aFilename, sizeof(aFilename));
	if(File)
	{
		io_close(File);
		pDefaultFont = TextRender()->LoadFont(aFilename);
		TextRender()->SetDefaultFont(pDefaultFont);
	}
	if(!pDefaultFont)
		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "gameclient", "failed to load font. filename='fonts/DejaVuSans.ttf'");

	g_Config.m_ClThreadsoundloading = 0;

	// setup load amount
	gs_LoadTotal = g_pData->m_NumImages;
	gs_LoadCurrent = 0;
	if(!g_Config.m_ClThreadsoundloading)
		gs_LoadTotal += g_pData->m_NumSounds;
	
	// load textures
	for(int i = 0; i < g_pData->m_NumImages; i++)
	{
		g_GameClient.m_pMenus->RenderLoading(gs_LoadCurrent/(float)gs_LoadTotal);
		g_pData->m_aImages[i].m_Id = Graphics()->LoadTexture(g_pData->m_aImages[i].m_pFilename, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0);
		gs_LoadCurrent++;
	}

	// load skins
	::gs_Skins.Init();
	
	// TODO: Refactor: fix threaded loading of sounds again
	// load sounds
	{
		bool DoRender = true;
		for(int s = 0; s < g_pData->m_NumSounds; s++)
		{
			if(DoRender)
				g_GameClient.m_pMenus->RenderLoading(gs_LoadCurrent/(float)gs_LoadTotal);
			for(int i = 0; i < g_pData->m_aSounds[s].m_NumSounds; i++)
			{
				int Id = Sound()->LoadWV(g_pData->m_aSounds[s].m_aSounds[i].m_pFilename);
				g_pData->m_aSounds[s].m_aSounds[i].m_Id = Id;
			}

			if(DoRender)
				gs_LoadCurrent++;
		}
	}
		
	/*if(config.cl_threadsoundloading)
		thread_create(load_sounds_thread, 0);
	else
		load_sounds_thread((void*)1);*/

	for(int i = 0; i < m_All.m_Num; i++)
		m_All.m_paComponents[i]->OnReset();
	
	int64 End = time_get();
	char aBuf[256];
	str_format(aBuf, sizeof(aBuf), "initialisation finished after %.2fms", ((End-Start)*1000)/(float)time_freq());
	Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "gameclient", aBuf);
	
	m_ServerMode = SERVERMODE_PURE;
}
Example #18
0
int CDataFileWriter::Finish()
{
    int ItemSize = 0;
    int TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize;
    int DataSize = 0;
    CDatafileHeader Header;

    // we should now write this file!
    if(DEBUG)
        dbg_msg("datafile", "writing");

    // calculate sizes
    for(int i = 0; i < m_NumItems; i++)
    {
        if(DEBUG)
            dbg_msg("datafile", "item=%d size=%d (%d)", i, m_aItems[i].m_Size, m_aItems[i].m_Size+sizeof(CDatafileItem));
        ItemSize += m_aItems[i].m_Size + sizeof(CDatafileItem);
    }


    for(int i = 0; i < m_NumDatas; i++)
        DataSize += m_aDatas[i].m_CompressedSize;

    // calculate the complete size
    TypesSize = m_NumItemTypes*sizeof(CDatafileItemType);
    HeaderSize = sizeof(CDatafileHeader);
    OffsetSize = m_NumItems*sizeof(int) + m_NumDatas*sizeof(int);
    FileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize;
    SwapSize = FileSize - DataSize;

    (void)SwapSize;

    if(DEBUG)
        dbg_msg("datafile", "num_m_aItemTypes=%d TypesSize=%d m_aItemsize=%d DataSize=%d", m_NumItemTypes, TypesSize, ItemSize, DataSize);

    // construct Header
    {
        Header.m_aId[0] = 'D';
        Header.m_aId[1] = 'A';
        Header.m_aId[2] = 'T';
        Header.m_aId[3] = 'A';
        Header.m_Version = 4;
        Header.m_Size = FileSize - 16;
        Header.m_Swaplen = SwapSize - 16;
        Header.m_NumItemTypes = m_NumItemTypes;
        Header.m_NumItems = m_NumItems;
        Header.m_NumRawData = m_NumDatas;
        Header.m_ItemSize = ItemSize;
        Header.m_DataSize = DataSize;

        // TODO: apply swapping
        // write Header
        if(DEBUG)
            dbg_msg("datafile", "HeaderSize=%d", sizeof(Header));
        io_write(m_File, &Header, sizeof(Header));
    }

    // write types
    for(int i = 0, Count = 0; i < 0xffff; i++)
    {
        if(m_aItemTypes[i].m_Num)
        {
            // write info
            CDatafileItemType Info;
            Info.m_Type = i;
            Info.m_Start = Count;
            Info.m_Num = m_aItemTypes[i].m_Num;
            if(DEBUG)
                dbg_msg("datafile", "writing type=%x start=%d num=%d", Info.m_Type, Info.m_Start, Info.m_Num);
            io_write(m_File, &Info, sizeof(Info));
            Count += m_aItemTypes[i].m_Num;
        }
    }

    // write item offsets
    for(int i = 0, Offset = 0; i < 0xffff; i++)
    {
        if(m_aItemTypes[i].m_Num)
        {
            // write all m_aItems in of this type
            int k = m_aItemTypes[i].m_First;
            while(k != -1)
            {
                if(DEBUG)
                    dbg_msg("datafile", "writing item offset num=%d offset=%d", k, Offset);
                io_write(m_File, &Offset, sizeof(Offset));
                Offset += m_aItems[k].m_Size + sizeof(CDatafileItem);

                // next
                k = m_aItems[k].m_Next;
            }
        }
    }

    // write data offsets
    for(int i = 0, Offset = 0; i < m_NumDatas; i++)
    {
        if(DEBUG)
            dbg_msg("datafile", "writing data offset num=%d offset=%d", i, Offset);
        io_write(m_File, &Offset, sizeof(Offset));
        Offset += m_aDatas[i].m_CompressedSize;
    }

    // write data uncompressed sizes
    for(int i = 0; i < m_NumDatas; i++)
    {
        /*
        if(DEBUG)
        	dbg_msg("datafile", "writing data offset num=%d offset=%d", i, offset);
        */
        io_write(m_File, &m_aDatas[i].m_UncompressedSize, sizeof(int));
    }

    // write m_aItems
    for(int i = 0; i < 0xffff; i++)
    {
        if(m_aItemTypes[i].m_Num)
        {
            // write all m_aItems in of this type
            int k = m_aItemTypes[i].m_First;
            while(k != -1)
            {
                CDatafileItem Item;
                Item.m_TypeAndId = (i<<16)|m_aItems[k].m_Id;
                Item.m_Size = m_aItems[k].m_Size;
                if(DEBUG)
                    dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_aItems[k].m_Id, m_aItems[k].m_Size);

                io_write(m_File, &Item, sizeof(Item));
                io_write(m_File, m_aItems[k].m_pData, m_aItems[k].m_Size);

                // next
                k = m_aItems[k].m_Next;
            }
        }
    }

    // write data
    for(int i = 0; i < m_NumDatas; i++)
    {
        if(DEBUG)
            dbg_msg("datafile", "writing data id=%d size=%d", i, m_aDatas[i].m_CompressedSize);
        io_write(m_File, m_aDatas[i].m_pCompressedData, m_aDatas[i].m_CompressedSize);
    }

    // free data
    for(int i = 0; i < m_NumItems; i++)
        mem_free(m_aItems[i].m_pData);


    io_close(m_File);

    if(DEBUG)
        dbg_msg("datafile", "done");
    return 0;
}
Example #19
0
void CAutoMapper::Load(const char* pTileName)
{
	char aPath[256];
	str_format(aPath, sizeof(aPath), "editor/%s.rules", pTileName);
	IOHANDLE RulesFile = m_pEditor->Storage()->OpenFile(aPath, IOFLAG_READ, IStorageTW::TYPE_ALL);
	if(!RulesFile)
		return;

	CLineReader LineReader;
	LineReader.Init(RulesFile);

	CConfiguration *pCurrentConf = 0;
	CIndexRule *pCurrentIndex = 0;

	char aBuf[256];

	// read each line
	while(char *pLine = LineReader.Get())
	{
		// skip blank/empty lines as well as comments
		if(str_length(pLine) > 0 && pLine[0] != '#' && pLine[0] != '\n' && pLine[0] != '\r'
			&& pLine[0] != '\t' && pLine[0] != '\v' && pLine[0] != ' ')
		{
			if(pLine[0]== '[')
			{
				// new configuration, get the name
				pLine++;

				CConfiguration NewConf;
				int ID = m_lConfigs.add(NewConf);
				pCurrentConf = &m_lConfigs[ID];

				str_copy(pCurrentConf->m_aName, pLine, str_length(pLine));
			}
			else
			{
				if(!str_comp_num(pLine, "Index", 5))
				{
					// new index
					int ID = 0;
					char aFlip[128] = "";

					sscanf(pLine, "Index %d %127s", &ID, aFlip);

					CIndexRule NewIndexRule;
					NewIndexRule.m_ID = ID;
					NewIndexRule.m_Flag = 0;
					NewIndexRule.m_RandomValue = 0;
					NewIndexRule.m_BaseTile = false;

					if(str_length(aFlip) > 0)
					{
						if(!str_comp(aFlip, "XFLIP"))
							NewIndexRule.m_Flag = TILEFLAG_VFLIP;
						else if(!str_comp(aFlip, "YFLIP"))
							NewIndexRule.m_Flag = TILEFLAG_HFLIP;
					}

					// add the index rule object and make it current
					int ArrayID = pCurrentConf->m_aIndexRules.add(NewIndexRule);
					pCurrentIndex = &pCurrentConf->m_aIndexRules[ArrayID];
				}
				else if(!str_comp_num(pLine, "BaseTile", 8) && pCurrentIndex)
				{
					pCurrentIndex->m_BaseTile = true;
				}
				else if(!str_comp_num(pLine, "Pos", 3) && pCurrentIndex)
				{
					int x = 0, y = 0;
					char aValue[128];
					int Value = CPosRule::EMPTY;
					bool IndexValue = false;

					sscanf(pLine, "Pos %d %d %127s", &x, &y, aValue);

					if(!str_comp(aValue, "FULL"))
						Value = CPosRule::FULL;
					else if(!str_comp_num(aValue, "INDEX", 5))
					{
						sscanf(pLine, "Pos %*d %*d INDEX %d", &Value);
						IndexValue = true;
					}

					CPosRule NewPosRule = {x, y, Value, IndexValue};
					pCurrentIndex->m_aRules.add(NewPosRule);
				}
				else if(!str_comp_num(pLine, "Random", 6) && pCurrentIndex)
				{
					sscanf(pLine, "Random %d", &pCurrentIndex->m_RandomValue);
				}
			}
		}
	}

	io_close(RulesFile);

	str_format(aBuf, sizeof(aBuf),"loaded %s", aPath);
	m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", aBuf);

	m_FileLoaded = true;
}
Example #20
0
int main(int argc, char **argv)
{
	if (argc > 1)
		while (++argv, --argc) {
			if (!strcmp("-c", argv[0]))
				color_on = 1;
			else if (!strcmp("-h", argv[0]))
				printf("liblisp unit tests\n\tusage ./%s (-c)? (-h)?\n", argv[0]);
			else
				printf("unknown argument '%s'\n", argv[0]);
		}

	unit_test_start("liblisp");
	{
		print_note("util.c");

		test(is_number("0xfAb"));
		test(is_number("-01234567"));
		test(is_number("+1000000000000000000000000000003"));
		test(!is_number(""));
		test(!is_number("+"));
		test(!is_number("-"));

		test(unbalanced("(((", '(', ')') > 0);
		test(unbalanced("))",  '(', ')') < 0);
		test(unbalanced("",    '(', ')') == 0);
		test(unbalanced("\"(", '(', ')') == 0);
		test(unbalanced("( \"))))(()()()(()\\\"())\")",  '(', ')') == 0);
		test(unbalanced("(a (b) c (d (e (f) \")\" g)))", '(', ')') == 0);
		test(unbalanced("((a b) c", '(', ')')  > 0);

		test(!is_fnumber(""));
		test(!is_fnumber("1e"));
		test(!is_fnumber("-1e"));
		test(!is_fnumber("1-e"));
		test(is_fnumber("+0."));
		test(is_fnumber("123"));	/*this passes, see header */
		test(is_fnumber("1e-3"));
		test(is_fnumber("1.003e+34"));
		test(is_fnumber("1e34"));
		test(is_fnumber("93.04"));

		test(match("", ""));
		test(match("abc", "abc"));
		test(!match("abC", "abc"));
		test(match("aaa*", "aaaXX"));
		test(!match("aaa*", "XXaaaXX"));
		test(match(".bc", "abc"));
		test(match("a.c", "aXc"));
		test(!match("a\\.c", "aXc"));
		test(match("a\\.c", "a.c"));

		char *s = NULL;
		state(s = vstrcatsep(",", "a", "b", "c", "", "foo", "bar", NULL));
		test(!sstrcmp("a,b,c,,foo,bar", s));
		free(s);

		char *t = NULL, *s1 = "Hello,", *s2 = " World!";
		state(t = calloc(16, 1));
		state(strcpy(t, s1));
		test(((size_t) (lstrcatend(t, s2) - t)) == (strlen(s1) + strlen(s2)));
		free(t);

		/*test tr, or translate, functionality */
		size_t trinsz = 0;
		uint8_t trout[128] = { 0 }, *trin = (uint8_t *) "aaabbbcdaacccdeeefxxxa";
		tr_state_t *tr1;
		state(tr1 = tr_new());
		state(trinsz = strlen((char *)trin));
		test(tr_init(tr1, "", (uint8_t *) "abc", (uint8_t *) "def") == TR_OK);
		test(tr_block(tr1, trin, trout, trinsz) == trinsz);
		test(!strcmp((char *)trout, "dddeeefdddfffdeeefxxxd"));
		test(tr_init(tr1, "s", (uint8_t *) "abc", (uint8_t *) "def") == TR_OK);
		state(memset(trout, 0, 128));
		test(tr_block(tr1, trin, trout, trinsz) <= trinsz);
		test(!strcmp((char *)trout, "defddfdeeefxxxd"));
		state(tr_delete(tr1));

		/*know collisions for the djb2 hash algorithm */
		test(djb2("heliotropes", strlen("heliotropes")) ==
		     djb2("neurospora", strlen("neurospora")));
		test(djb2("depravement", strlen("depravement")) ==
		     djb2("serafins", strlen("serafins")));
		/*should not collide */
		test(djb2("heliotropes", strlen("heliotropes")) !=
		     djb2("serafins", strlen("serafins")));
	}

	{ /*io.c test */
		io_t *in, *out;
		print_note("io.c");

		/*string input */
		static const char hello[] = "Hello\n";
		/**@note io_sin currently duplicates "hello" internally*/
		state(in = io_sin(hello, strlen(hello)));
		test(io_is_in(in));
		test(io_getc(in) == 'H');
		test(io_getc(in) == 'e');
		test(io_getc(in) == 'l');
		test(io_getc(in) == 'l');
		test(io_getc(in) == 'o');
		test(io_getc(in) == '\n');
		test(io_getc(in) == EOF);
		test(io_getc(in) == EOF);
		test(!io_error(in));
		test(io_seek(in, 0, SEEK_SET) >= 0);
		test(io_getc(in) == 'H');
		test(io_seek(in, 3, SEEK_SET) >= 0);
		test(io_getc(in) == 'l');
		test(io_ungetc('x', in) == 'x');
		test(io_getc(in) == 'x');
		test(io_getc(in) == 'o');
		state(io_close(in));

		/*string output */
		char *s = NULL;
		static const char hello_world[] = "Hello,\n\tWorld!\n";
		/**@note io_sin currently duplicates hello_world internally*/
		state(in = io_sin(hello_world, strlen(hello_world))); 
		test(!strcmp(s = io_getline(in), "Hello,"));
		s = (free(s), NULL);
		test(!strcmp(s = io_getline(in), "\tWorld!"));
		s = (free(s), NULL);
		test(!io_getline(in));
		test(io_seek(in, 0, SEEK_SET) >= 0);
		test(!strcmp(s = io_getdelim(in, EOF), "Hello,\n\tWorld!\n"));
		s = (free(s), NULL);
		state(io_close(in));

		state(out = io_sout(1));
		test(io_puts("Hello, World", out) != EOF);
		test(!strcmp("Hello, World", io_get_string(out)));
		test(io_putc('\n', out) != EOF);
		test(!strcmp("Hello, World\n", io_get_string(out)));
		test(io_seek(out, -6, SEEK_CUR) >= 0);
		test(io_puts("Mars\n", out) != EOF);
		test(!strcmp("Hello, Mars\n\n", io_get_string(out)));
		free(io_get_string(out));
		state(io_close(out));

		static const char block_in[16] = {1, 3, 4, 6};
		static char block_out[16] = {0};
		state((in = io_sin(block_in, 16)));
		test(io_getc(in) == 1);
		test(io_read(block_out, 15, in) == 15);
		test(!memcmp(block_out, block_in+1, 15));

		state(io_close(in));
	}

	{ /* hash.c hash table tests */
		hash_table_t *h = NULL;
		print_note("hash.c");
		state(h = hash_create(1));
		return_if(!h);
		test(!hash_insert(h, "key1", "val1"));
		test(!hash_insert(h, "key2", "val2"));
		/* assuming the hash algorithm is djb2, then
		 *  "heliotropes"  collides with "neurospora"
		 *  "depravement"  collides with "serafins"
		 *  "playwright"   collides with "snush" (for djb2a)
		 * See:
		 * <https://programmers.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed> */
		test(!hash_insert(h, "heliotropes", "val3"));
		test(!hash_insert(h, "neurospora", "val4"));
		test(!hash_insert(h, "depravement", "val5"));
		test(!hash_insert(h, "serafins", "val6"));
		test(!hash_insert(h, "playwright", "val7"));
		test(!hash_insert(h, "snush", "val8"));
		test(!hash_insert(h, "", "val9"));
		test(!hash_insert(h, "nil", ""));
		test(!hash_insert(h, "a", "x"));
		test(!hash_insert(h, "a", "y"));
		test(!hash_insert(h, "a", "z"));
		test(!sstrcmp("val1", hash_lookup(h, "key1")));
		test(!sstrcmp("val2", hash_lookup(h, "key2")));
		test(!sstrcmp("val3", hash_lookup(h, "heliotropes")));
		test(!sstrcmp("val4", hash_lookup(h, "neurospora")));
		test(!sstrcmp("val5", hash_lookup(h, "depravement")));
		test(!sstrcmp("val6", hash_lookup(h, "serafins")));
		test(!sstrcmp("val7", hash_lookup(h, "playwright")));
		test(!sstrcmp("val8", hash_lookup(h, "snush")));
		test(!sstrcmp("val9", hash_lookup(h, "")));
		test(!sstrcmp("", hash_lookup(h, "nil")));
		test(!sstrcmp("z", hash_lookup(h, "a")));
		test(hash_get_load_factor(h) <= 0.75f);

		state(hash_destroy(h));
	}

	{			/* lisp.c (and the lisp interpreter in general) */
		lisp_t *l;

		print_note("lisp.c");
		/*while unit testing eschews state being held across tests it is makes
		 *little sense in this case*/
		state(l = lisp_init());
		state(io_close(lisp_get_logging(l)));
		test(!lisp_set_logging(l, io_nout()));
		return_if(!l);
		test(!lisp_eval_string(l, ""));
		test(is_int(lisp_eval_string(l, "2")));
		test(get_int(lisp_eval_string(l, "(+ 2 2)")) == 4);
		test(get_int(lisp_eval_string(l, "(* 3 2)")) == 6);

		lisp_cell_t *x = NULL, *y = NULL, *z = NULL;
		char *t = NULL;
		state(x = lisp_intern(l, lstrdup_or_abort("foo")));
		state(y = lisp_intern(l, t = lstrdup_or_abort("foo")));	/*this one needs freeing! */
		state(z = lisp_intern(l, lstrdup_or_abort("bar")));
		test(x == y && x != NULL);
		test(x != z);
		free(t);	/*free the non-interned string */

		test(is_proc(lisp_eval_string(l, "(define square (lambda (x) (* x x)))")));
		test(get_int(lisp_eval_string(l, "(square 4)")) == 16);

		test(!is_list(cons(l, gsym_tee(), gsym_tee())));
		test(is_list(cons(l, gsym_tee(), gsym_nil())));
		test(!is_list(cons(l, gsym_nil(), cons(l, gsym_tee(), gsym_tee()))));
		test(is_list(mk_list(l, gsym_tee(), gsym_nil(), gsym_tee(), NULL)));

		test(gsym_error() == lisp_eval_string(l, "(> 'a 1)"));
		test(is_sym(x));
		test(is_asciiz(x));
		test(!is_str(x));
		test(gsym_error() == lisp_eval_string(l, "(eval (cons quote 0))"));

		char *serial = NULL;
		test(!strcmp((serial = lisp_serialize(l, cons(l, gsym_tee(), gsym_error()))), "(t . error)"));
		state(free(serial));

		state(lisp_destroy(l));
	}
	return unit_test_end("liblisp");	/*should be zero! */
}
Example #21
0
void CGameClient::OnInit()
{
	m_pGraphics = Kernel()->RequestInterface<IGraphics>();

	// propagate pointers
	m_UI.SetGraphics(Graphics(), TextRender());
	m_RenderTools.m_pGraphics = Graphics();
	m_RenderTools.m_pUI = UI();
	
	int64 Start = time_get();

	// set the language
	g_Localization.Load(g_Config.m_ClLanguagefile, Storage(), Console());

	// TODO: this should be different
	// setup item sizes
	for(int i = 0; i < NUM_NETOBJTYPES; i++)
		Client()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i));

	// load default font
	static CFont *pDefaultFont = 0;
	char aFilename[512];
	IOHANDLE File = Storage()->OpenFile("fonts/DejaVuSans.ttf", IOFLAG_READ, IStorage::TYPE_ALL, aFilename, sizeof(aFilename));
	if(File)
	{
		io_close(File);
		pDefaultFont = TextRender()->LoadFont(aFilename);
		TextRender()->SetDefaultFont(pDefaultFont);
	}
	if(!pDefaultFont)
		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "gameclient", "failed to load font. filename='fonts/DejaVuSans.ttf'");

	// init all components
	for(int i = m_All.m_Num-1; i >= 0; --i)
		m_All.m_paComponents[i]->OnInit();

	// setup load amount// load textures
	for(int i = 0; i < g_pData->m_NumImages; i++)
	{
		g_pData->m_aImages[i].m_Id = Graphics()->LoadTexture(g_pData->m_aImages[i].m_pFilename, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0);
		g_GameClient.m_pMenus->RenderLoading();
	}

	for(int i = 0; i < m_All.m_Num; i++)
		m_All.m_paComponents[i]->OnReset();

	int64 End = time_get();
	char aBuf[256];
	str_format(aBuf, sizeof(aBuf), "initialisation finished after %.2fms", ((End-Start)*1000)/(float)time_freq());
	Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "gameclient", aBuf);

	m_ServerMode = SERVERMODE_PURE;

	m_DDRaceMsgSent = false;
	m_ShowOthers = -1;
	m_IsDDRace = false;

	// Set free binds to DDRace binds if it's active
	if(!g_Config.m_ClDDRaceBindsSet && g_Config.m_ClDDRaceBinds)
		gs_Binds.SetDDRaceBinds(true);
}
Example #22
0
PDBfile *
lite_PD_create (char *name) {

   char str[MAXLINE];
   PDBfile *file;
   static FILE *fp;

   file = NULL;

   switch (setjmp(_lite_PD_create_err)) {
   case ABORT:
      if (fp) io_close(fp);
      return(NULL);
   case ERR_FREE:
      return(file);
   default:
      memset(lite_PD_err, 0, MAXLINE);
      break;
   }

   /*
    * Open the file.
    */
   strncpy(str, name, sizeof(str));
   str[sizeof(str)-1] = '\0';
   fp = io_open(str, BINARY_MODE_WPLUS);
   if (!fp) lite_PD_error("CAN'T CREATE FILE - PD_CREATE", PD_CREATE);

   if (lite_PD_buffer_size != -1) {
      if (io_setvbuf(fp, NULL, _IOFBF, (size_t) lite_PD_buffer_size)) {
	 lite_PD_error("CAN'T SET FILE BUFFER - PD_CREATE", PD_OPEN);
      }
   }

   /*
    * Make the PDBfile.
    */
   file = _lite_PD_mk_pdb(str, lite_PD_DEF_CREATM);
   if (file == NULL) {
      lite_PD_error("CAN'T ALLOCATE PDBFILE - PD_CREATE", PD_OPEN);
   }

   file->stream = fp;
   file->mode   = PD_CREATE;

   /*
    * Set the file data conversion standard - and yes someone might pick
    * a target standard which is the current standard
    */
   file->std   = _lite_PD_copy_standard(file->host_std);
   file->align = _lite_PD_copy_alignment(file->host_align);
   if (lite_REQ_STANDARD != NULL) {
      if (!_lite_PD_compare_std(lite_REQ_STANDARD, file->std,
				lite_REQ_ALIGNMENT, file->align)) {
	 _lite_PD_rl_standard(file->std);
	 file->std   = _lite_PD_copy_standard(lite_REQ_STANDARD);
	 _lite_PD_rl_alignment(file->align);
	 file->align = _lite_PD_copy_alignment(lite_REQ_ALIGNMENT);
      }
      lite_REQ_STANDARD = NULL;
   }

   /*
    * Write the ASCII header.
    */
   io_printf(fp, "%s\n", HeadTok);
   if (io_flush(fp)) {
      lite_PD_error("FFLUSH FAILED BEFORE HEADER - PD_CREATE", PD_CREATE);
   }

   /*
    * Write the primitive data type formats.
    */
   if (!_lite_PD_wr_format(file)) {
      lite_PD_error("FAILED TO WRITE FORMATS - PD_CREATE", PD_CREATE);
   }

   /*
    * Record the current file position as the location of the symbol table
    * address and sequentially the chart address
    */
   if ((file->headaddr = io_tell(fp)) == -1L) {
      lite_PD_error("CAN'T FIND HEADER ADDRESS - PD_CREATE", PD_CREATE);
   }

   /*
    * Initialize the pdb system defs and structure chart.
    */
   _lite_PD_init_chrt(file);

   if (io_flush(fp)) {
      lite_PD_error("FFLUSH FAILED AFTER HEADER - PD_CREATE", PD_CREATE);
   }

   memset(str, 0, PAD_SIZE);
   if (io_write(str, (size_t) 1, PAD_SIZE, fp) != PAD_SIZE) {
      lite_PD_error("FAILED TO PAD FILE FOR MPW - PD_CREATE", PD_CREATE);
   }

   file->chrtaddr = file->headaddr + 128L;
   if (io_seek(fp, file->chrtaddr, SEEK_SET)) {
      lite_PD_error("FAILED TO FIND START OF DATA - PD_CREATE", PD_CREATE);
   }

   file->system_version = PDB_SYSTEM_VERSION;
   file->date           = lite_SC_date();

   /*
    * Create the top-level directory
    */
   lite_PD_mkdir(file,"/");
   return(file);
}
Example #23
0
int datafile_finish(DATAFILE_OUT *df)
{
	int itemsize = 0;
	int i, count, offset;
	int typessize, headersize, offsetsize, filesize, swapsize;
	int datasize = 0;
	DATAFILE_ITEM_TYPE info;
	DATAFILE_ITEM itm;
	DATAFILE_HEADER header;

	/* we should now write this file! */
	if(DEBUG)
		dbg_msg("datafile", "writing");

	/* calculate sizes */
	for(i = 0; i < df->num_items; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "item=%d size=%d (%d)", i, df->items[i].size, df->items[i].size+sizeof(DATAFILE_ITEM));
		itemsize += df->items[i].size + sizeof(DATAFILE_ITEM);
	}
	
	
	for(i = 0; i < df->num_datas; i++)
		datasize += df->datas[i].compressed_size;
	
	/* calculate the complete size */
	typessize = df->num_item_types*sizeof(DATAFILE_ITEM_TYPE);
	headersize = sizeof(DATAFILE_HEADER);
	offsetsize = df->num_items*sizeof(int) + df->num_datas*sizeof(int);
	filesize = headersize + typessize + offsetsize + itemsize + datasize;
	swapsize = filesize - datasize;
	
	(void)swapsize;
	
	if(DEBUG)
		dbg_msg("datafile", "num_item_types=%d typessize=%d itemsize=%d datasize=%d", df->num_item_types, typessize, itemsize, datasize);
	
	/* construct header */
	{
		header.id[0] = 'D';
		header.id[1] = 'A';
		header.id[2] = 'T';
		header.id[3] = 'A';
		header.version = 4;
		header.size = filesize - 16;
		header.swaplen = swapsize - 16;
		header.num_item_types = df->num_item_types;
		header.num_items = df->num_items;
		header.num_raw_data = df->num_datas;
		header.item_size = itemsize;
		header.data_size = datasize;
		
		/* TODO: apply swapping */
		/* write header */
		if(DEBUG)
			dbg_msg("datafile", "headersize=%d", sizeof(header));
		io_write(df->file, &header, sizeof(header));
	}
	
	/* write types */
	for(i = 0, count = 0; i < 0xffff; i++)
	{
		if(df->item_types[i].num)
		{
			/* write info */
			info.type = i;
			info.start = count;
			info.num = df->item_types[i].num;
			if(DEBUG)
				dbg_msg("datafile", "writing type=%x start=%d num=%d", info.type, info.start, info.num);
			io_write(df->file, &info, sizeof(info));
			count += df->item_types[i].num;
		}
	}
	
	/* write item offsets */
	for(i = 0, offset = 0; i < 0xffff; i++)
	{
		if(df->item_types[i].num)
		{
			/* write all items in of this type */
			int k = df->item_types[i].first;
			while(k != -1)
			{
				if(DEBUG)
					dbg_msg("datafile", "writing item offset num=%d offset=%d", k, offset);
				io_write(df->file, &offset, sizeof(offset));
				offset += df->items[k].size + sizeof(DATAFILE_ITEM);
				
				/* next */
				k = df->items[k].next;
			}
		}
	}
	
	/* write data offsets */
	for(i = 0, offset = 0; i < df->num_datas; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "writing data offset num=%d offset=%d", i, offset);
		io_write(df->file, &offset, sizeof(offset));
		offset += df->datas[i].compressed_size;
	}

	/* write data uncompressed sizes */
	for(i = 0, offset = 0; i < df->num_datas; i++)
	{
		/*
		if(DEBUG)
			dbg_msg("datafile", "writing data offset num=%d offset=%d", i, offset);
		*/
		io_write(df->file, &df->datas[i].uncompressed_size, sizeof(int));
	}
	
	/* write items */
	for(i = 0; i < 0xffff; i++)
	{
		if(df->item_types[i].num)
		{
			/* write all items in of this type */
			int k = df->item_types[i].first;
			while(k != -1)
			{
				itm.type_and_id = (i<<16)|df->items[k].id;
				itm.size = df->items[k].size;
				if(DEBUG)
					dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, df->items[k].id, df->items[k].size);
				
				io_write(df->file, &itm, sizeof(itm));
				io_write(df->file, df->items[k].data, df->items[k].size);
				
				/* next */
				k = df->items[k].next;
			}
		}
	}
	
	/* write data */
	for(i = 0; i < df->num_datas; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "writing data id=%d size=%d", i, df->datas[i].compressed_size);
		io_write(df->file, df->datas[i].compressed_data, df->datas[i].compressed_size);
	}

	/* free data */
	for(i = 0; i < df->num_items; i++)
		mem_free(df->items[i].data);

	
	io_close(df->file);
	mem_free(df);

	if(DEBUG)
		dbg_msg("datafile", "done");
	return 0;
}
Example #24
0
/*-------------------------------------------------------------------------
 * Function:	lite_PD_open
 *
 * Purpose:	Open an existing PDB file, extract the symbol table and
 *		structure chart.
 *
 * Return:	Success:	Ptr to the PDB file structure
 *
 *		Failure:	NULL
 *
 * Programmer:	Adapted from the PACT PDB library
 *		Mar  4, 1996 10:26 AM EST
 *
 * Modifications:
 *
 * 	Robb Matzke, 4 Mar 1996
 *	Fixed indentation.  Files can only be opened with mode `r'.
 *
 * 	Robb Matzke, 17 Apr 1996
 *	Added write capability back into the function, but it is protected
 *	with #ifdef PDB_WRITE.
 *
 *      Mark C. Miller, Fri Apr 13 22:37:56 PDT 2012
 *      Changed mode string checks to strchr to accomodate wider variety
 *      of mode characters for new hash table size and open modes.
 *
 *      Mark C. Miller, Thu Jun 14 13:25:02 PDT 2012
 *      Remove call to io_close in ABORT case. The file pointer may not
 *      have been properly initialized.
 *-------------------------------------------------------------------------
 */
PDBfile *
lite_PD_open (char *name, char *mode) {

   char		str[MAXLINE], *token;
   PDBfile 	*file=NULL;
   static FILE 	*fp;
   syment 	*ep;

#ifdef PDB_WRITE
   /*
    * If opened in write mode use PD_CREATE instead.
    */
   if (strchr(mode,'w')) return lite_PD_create (name);
#else
   assert (!strchr(mode,'r')) ;
#endif

   switch (setjmp(_lite_PD_open_err)) {
   case ABORT:
      if (fp) io_close(fp);
      return(NULL);
   case ERR_FREE:
      return(file);
   default:
      memset(lite_PD_err, 0, MAXLINE);
      break;
   }

   /*
    * Open the file
    */
   strcpy(str, name);

#ifdef PDB_WRITE
   fp = io_open(str, BINARY_MODE_RPLUS);
   if (fp == NULL) {
      if (strchr(mode,'r')) {
#endif
	 fp = io_open(str, BINARY_MODE_R);
	 if (fp == NULL) {
	    lite_PD_error("CAN'T OPEN FILE IN READ-ONLY MODE - PD_OPEN",
			  PD_OPEN);
	 }
#ifdef PDB_WRITE
      } else if (strchr(mode,'a')) {
	 return lite_PD_create (name);
      } else {
	 lite_PD_error("CAN'T OPEN FILE - PD_OPEN", PD_OPEN);
      }
   }
#endif

   if (lite_PD_buffer_size != -1) {
      if (io_setvbuf(fp, NULL, _IOFBF, (size_t) lite_PD_buffer_size)) {
	 lite_PD_error("CAN'T SET FILE BUFFER - PD_OPEN", PD_OPEN);
      }
   }

   file = _lite_PD_mk_pdb(str, mode);
   if (file == NULL) {
      lite_PD_error("CAN'T ALLOCATE PDBFILE - PD_OPEN", PD_OPEN);
   }
   file->stream = fp;
#ifdef PDB_WRITE
   if (strchr(mode,'a')) file->mode = PD_APPEND;
   else file->mode = PD_OPEN;
#else
   file->mode = PD_OPEN ;
#endif

   /*
    * Attempt to read an ASCII header.
    */
   if (io_seek(fp, 0L, SEEK_SET)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("FSEEK FAILED TO FIND ORIGIN - PD_OPEN", PD_OPEN);
   }
   if (_lite_PD_rfgets(str, MAXLINE, fp) == NULL) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T READ THE FILE HEADER - PD_OPEN", PD_OPEN);
   }

   /*
    * The first token should be the identifying header token.
    */
   token = strtok(str, " ");
   if (token == NULL) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("FILE HEADER NOT ASCII - PD_OPEN", PD_OPEN);
   }


   if (strcmp(token, HeadTok) == 0) {
      /*
       * This is a PDB_SYSTEM_VERSION 2 or later file.
       * Read the primitive data type formats which set the standard.
       */
      if (!_lite_PD_rd_format(file)) {
         _lite_PD_rl_pdb(file); 
	 lite_PD_error("FAILED TO READ FORMATS - PD_OPEN", PD_OPEN);
      }
      
   } else if (strcmp(token, OldHeadTok) == 0) {
      /*
       * This is a pre-PDB_SYSTEM_VERSION 2 style file. The second token
       * is the machine type that wrote the file.  Set the file->std for
       * machine type for PD_open the file->std is always the PDBfile standard.
       * Alignment issues are not properly handled before PDB_SYSTEM_VERSION 3
       * but do the best that we can.
       */
      token = strtok(NULL, " ");
      if (token == NULL)
      {
         _lite_PD_rl_pdb(file); 
         lite_PD_error("INCOMPLETE HEADER - PD_OPEN", PD_OPEN);
      }
      switch (atoi(token)) {
      case IEEE_32_64:
	 file->std   = _lite_PD_copy_standard(&lite_IEEEA_STD);
	 file->align = _lite_PD_copy_alignment(&lite_M68000_ALIGNMENT);
	 break;
      case IEEE_32_96:
	 file->std   = _lite_PD_copy_standard(&lite_IEEEB_STD);
	 file->align = _lite_PD_copy_alignment(&lite_M68000_ALIGNMENT);
	 break;
      case INTEL_X86:
	 file->std   = _lite_PD_copy_standard(&lite_INTELA_STD);
	 file->align = _lite_PD_copy_alignment(&lite_INTELA_ALIGNMENT);
	 break;
      case CRAY_64:
	 file->std   = _lite_PD_copy_standard(&lite_CRAY_STD);
	 file->align = _lite_PD_copy_alignment(&lite_UNICOS_ALIGNMENT);
	 break;
      case VAX_11:
	 file->std   = _lite_PD_copy_standard(&lite_VAX_STD);
	 file->align = _lite_PD_copy_alignment(&lite_DEF_ALIGNMENT);
	 break;
      default:
	 file->std   = _lite_PD_copy_standard(&lite_DEF_STD);
	 file->align = _lite_PD_copy_alignment(&lite_DEF_ALIGNMENT);
	 break;
      }

      /*
       * To correctly handle the situation in which many PDBfiles are open
       * at the same time always try to latch on to the file->host_std.
       * Alignment issues are not properly handled before PDB_SYSTEM_VERSION 3
       * but do the best that we can
       */
      if (_lite_PD_compare_std(file->host_std, file->std,
			       file->host_align, file->align)) {
	 _lite_PD_rl_standard(file->std);
	 file->std   = _lite_PD_copy_standard(file->host_std);
	 _lite_PD_rl_alignment(file->align);
	 file->align = _lite_PD_copy_alignment(file->host_align);
      }
   } else {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("BAD FILE HEADER - PD_OPEN", PD_OPEN);
   }

   /*
    * Record the current file position as the location of the symbol table
    * address and sequentially the chart address.
    */
   file->headaddr = io_tell(fp);
   if (file->headaddr == -1L) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T FIND HEADER ADDRESS - PD_OPEN", PD_OPEN);
   }

   /*
    * Read the address of the symbol table and structure chart.
    */
   if (_lite_PD_rfgets(str, MAXLINE, fp) == NULL) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T READ SYMBOL TABLE ADDRESS - PD_OPEN", PD_OPEN);
   }

   token = strtok(str, "\001");
   if (token == NULL) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("BAD STRUCTURE CHART ADDRESS - PD_OPEN", PD_OPEN);
   }
   file->chrtaddr = atol(token);

   token = strtok(NULL, "\001");
   if (token == NULL) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("BAD SYMBOL TABLE ADDRESS - PD_OPEN", PD_OPEN);
   }
   file->symtaddr = atol(token);

   /*
    * Read the symbol table first so that the file pointer is positioned
    * to the "extra" information, then read the "extra's" to get the
    * alignment data, and finish with the structure chart which needs
    * the alignment data
    */

   /*
    * Read the symbol table.
    */
   if (io_seek(fp, file->symtaddr, SEEK_SET)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("FSEEK FAILED SYMBOL TABLE - PD_OPEN", PD_OPEN);
   }
   if (!_lite_PD_rd_symt(file)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T READ SYMBOL TABLE - PD_OPEN", PD_OPEN);
   }

   /*
    * Read the miscellaneous data.
    */
   if (!_lite_PD_rd_extras(file)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T READ MISCELLANEOUS DATA - PD_OPEN", PD_OPEN);
   }

   /*
    * Initialize the pdb system defs and structure chart.
    */
   _lite_PD_init_chrt(file);

   /*
    * Read the structure chart.
    */
   if (io_seek(fp, file->chrtaddr, SEEK_SET)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("FSEEK FAILED STRUCTURE CHART - PD_OPEN", PD_OPEN);
   }
   if (!_lite_PD_rd_chrt(file)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T READ STRUCTURE CHART - PD_OPEN", PD_OPEN);
   }

   ep = lite_PD_inquire_entry(file, PDB_ATTRIBUTE_TABLE, TRUE, NULL);
   if (ep != NULL) {
      if (!lite_PD_read(file, PDB_ATTRIBUTE_TABLE, &file->attrtab)) {
	 lite_PD_close(file);
	 lite_PD_error("FAILED TO READ ATTRIBUTE TABLE - PD_OPEN", PD_OPEN);
      }
      _lite_PD_convert_attrtab(file);
      file->chrtaddr = PD_entry_address(ep);
      _lite_PD_rl_syment(ep);
      lite_SC_hash_rem(_lite_PD_fixname(file, PDB_ATTRIBUTE_TABLE),
		       file->symtab);
   } else {
      file->attrtab = NULL;
   }

   /*
    * Position the file pointer to the location of the structure chart.
    */
   if (io_seek(fp, file->chrtaddr, SEEK_SET)) {
      lite_PD_close(file);
      lite_PD_error("FSEEK FAILED CHART - PD_OPEN", PD_OPEN);
   }

   return(file);
}
Example #25
0
void CCountryFlags::LoadCountryflagsIndexfile()
{
	IOHANDLE File = Storage()->OpenFile("countryflags/index.txt", IOFLAG_READ, IStorage::TYPE_ALL);
	if(!File)
	{
		Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", "couldn't open index file");
		return;
	}

	char aOrigin[128];
	CLineReader LineReader;
	LineReader.Init(File);
	char *pLine;
	while((pLine = LineReader.Get()))
	{
		if(!str_length(pLine) || pLine[0] == '#') // skip empty lines and comments
			continue;

		str_copy(aOrigin, pLine, sizeof(aOrigin));
		char *pReplacement = LineReader.Get();
		if(!pReplacement)
		{
			Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", "unexpected end of index file");
			break;
		}

		if(pReplacement[0] != '=' || pReplacement[1] != '=' || pReplacement[2] != ' ')
		{
			char aBuf[128];
			str_format(aBuf, sizeof(aBuf), "malform replacement for index '%s'", aOrigin);
			Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf);
			continue;
		}

		int CountryCode = str_toint(pReplacement+3);
		if(CountryCode < CODE_LB || CountryCode > CODE_UB)
		{
			char aBuf[128];
			str_format(aBuf, sizeof(aBuf), "country code '%i' not within valid code range [%i..%i]", CountryCode, CODE_LB, CODE_UB);
			Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf);
			continue;
		}

		// load the graphic file
		char aBuf[128];
		CImageInfo Info;
		if(g_Config.m_ClLoadCountryFlags)
		{
			str_format(aBuf, sizeof(aBuf), "countryflags/%s.png", aOrigin);
			if(!Graphics()->LoadPNG(&Info, aBuf, IStorage::TYPE_ALL))
			{
				char aMsg[128];
				str_format(aMsg, sizeof(aMsg), "failed to load '%s'", aBuf);
				Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aMsg);
				continue;
			}
		}

		// add entry
		CCountryFlag CountryFlag;
		CountryFlag.m_CountryCode = CountryCode;
		str_copy(CountryFlag.m_aCountryCodeString, aOrigin, sizeof(CountryFlag.m_aCountryCodeString));
		if(g_Config.m_ClLoadCountryFlags)
		{
			CountryFlag.m_Texture = Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);
			mem_free(Info.m_pData);
		}
		
		if(g_Config.m_Debug)
		{
			str_format(aBuf, sizeof(aBuf), "loaded country flag '%s'", aOrigin);
			Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf);
		}
		m_aCountryFlags.add_unsorted(CountryFlag);
	}
	io_close(File);
	m_aCountryFlags.sort_range();

	// find index of default item
	int DefaultIndex = 0, Index = 0;
	for(sorted_array<CCountryFlag>::range r = m_aCountryFlags.all(); !r.empty(); r.pop_front(), ++Index)
		if(r.front().m_CountryCode == -1)
		{
			DefaultIndex = Index;
			break;
		}
	
	// init LUT
	if(DefaultIndex != 0)
		for(int i = 0; i < CODE_RANGE; ++i)
			m_CodeIndexLUT[i] = DefaultIndex;
	else
		mem_zero(m_CodeIndexLUT, sizeof(m_CodeIndexLUT));
	for(int i = 0; i < m_aCountryFlags.size(); ++i)
		m_CodeIndexLUT[max(0, (m_aCountryFlags[i].m_CountryCode-CODE_LB)%CODE_RANGE)] = i;
}
Example #26
0
int
deliver_smtp_deliver(struct deliver_ctx *dctx, struct actitem *ti)
{
	struct account			*a = dctx->account;
	struct mail			*m = dctx->mail;
	struct deliver_smtp_data	*data = ti->data;
	int				 done, code;
	struct io			*io;
	char				*cause, *to, *from, *line, *ptr, *lbuf;
	enum deliver_smtp_state		 state;
	size_t				 len, llen;

	io = connectproxy(&data->server,
	    conf.verify_certs, conf.proxy, IO_CRLF, conf.timeout, &cause);
	if (io == NULL) {
		log_warnx("%s: %s", a->name, cause);
		xfree(cause);
		return (DELIVER_FAILURE);
	}
	if (conf.debug > 3 && !conf.syslog)
		io->dup_fd = STDOUT_FILENO;

	llen = IO_LINESIZE;
	lbuf = xmalloc(llen);

	if (conf.host_fqdn != NULL)
		xasprintf(&ptr, "%s@%s", dctx->udata->name, conf.host_fqdn);
	else
		xasprintf(&ptr, "%s@%s", dctx->udata->name, conf.host_name);
	if (data->to.str == NULL)
		to = xstrdup(ptr);
	else {
		to = replacestr(&data->to, m->tags, m, &m->rml);
		if (to == NULL || *to == '\0') {
			xasprintf(&cause, "%s: empty to", a->name);
			from = NULL;
			goto error;
		}
	}
	if (data->from.str == NULL)
		from = xstrdup(ptr);
	else {
		from = replacestr(&data->from, m->tags, m, &m->rml);
		if (from == NULL || *from == '\0') {
			xasprintf(&cause, "%s: empty from", a->name);
			goto error;
		}
	}
	xfree(ptr);

	state = SMTP_CONNECTING;
	line = NULL;
	done = 0;
	do {
		switch (io_pollline2(io,
		    &line, &lbuf, &llen, conf.timeout, &cause)) {
		case 0:
			cause = xstrdup("connection unexpectedly closed");
			goto error;
		case -1:
			goto error;
		}
		code = deliver_smtp_code(line);

		cause = NULL;
		switch (state) {
		case SMTP_CONNECTING:
			if (code != 220)
				goto error;
			state = SMTP_HELO;
			if (conf.host_fqdn != NULL)
				io_writeline(io, "HELO %s", conf.host_fqdn);
			else
				io_writeline(io, "HELO %s", conf.host_name);
			break;
		case SMTP_HELO:
			if (code != 250)
				goto error;
			state = SMTP_FROM;
			io_writeline(io, "MAIL FROM:<%s>", from);
			break;
		case SMTP_FROM:
			if (code != 250)
				goto error;
			state = SMTP_TO;
			io_writeline(io, "RCPT TO:<%s>", to);
			break;
		case SMTP_TO:
			if (code != 250)
				goto error;
			state = SMTP_DATA;
			io_writeline(io, "DATA");
			break;
		case SMTP_DATA:
			if (code != 354)
				goto error;
			line_init(m, &ptr, &len);
			while (ptr != NULL) {
				if (len > 1) {
					if (*ptr == '.')
						io_write(io, ".", 1);
					io_write(io, ptr, len - 1);
				}
				io_writeline(io, NULL);

				/* Update if necessary. */
				if (io_update(io, conf.timeout, &cause) != 1)
					goto error;

				line_next(m, &ptr, &len);
			}
			state = SMTP_DONE;
			io_writeline(io, ".");
			io_flush(io, conf.timeout, NULL);
			break;
		case SMTP_DONE:
			if (code != 250)
				goto error;
			state = SMTP_QUIT;
			io_writeline(io, "QUIT");
			break;
		case SMTP_QUIT:
			/*
			 * Exchange sometimes refuses to accept QUIT as a valid
			 * command, but since we got a 250 the mail has been
			 * accepted. So, allow 500 here too.
			 */
			if (code != 500 && code != 221)
				goto error;
			done = 1;
			break;
		}
	} while (!done);

	xfree(lbuf);
	xfree(from);
	xfree(to);

	io_close(io);
	io_free(io);

	return (DELIVER_SUCCESS);

error:
	if (cause != NULL) {
		log_warnx("%s: %s", a->name, cause);
		xfree(cause);
	} else
		log_warnx("%s: unexpected response: %s", a->name, line);

	io_writeline(io, "QUIT");
	io_flush(io, conf.timeout, NULL);

	xfree(lbuf);
	if (from != NULL)
		xfree(from);
	if (to != NULL)
		xfree(to);

	io_close(io);
	io_free(io);

	return (DELIVER_FAILURE);
}
Example #27
0
void CAutoMapper::Load(const char* pTileName)
{
	char aPath[256];
	str_format(aPath, sizeof(aPath), "editor/%s.rules", pTileName);
	IOHANDLE RulesFile = m_pEditor->Storage()->OpenFile(aPath, IOFLAG_READ, IStorage::TYPE_ALL);
	if(!RulesFile)
		return;

	CLineReader LineReader;
	LineReader.Init(RulesFile);

	CConfiguration *pCurrentConf = 0;
	CRun *pCurrentRun = 0;
	CIndexRule *pCurrentIndex = 0;

	char aBuf[256];

	// read each line
	while(char *pLine = LineReader.Get())
	{
		// skip blank/empty lines as well as comments
		if(str_length(pLine) > 0 && pLine[0] != '#' && pLine[0] != '\n' && pLine[0] != '\r'
			&& pLine[0] != '\t' && pLine[0] != '\v' && pLine[0] != ' ')
		{
			if(pLine[0]== '[')
			{
				// new configuration, get the name
				pLine++;
				CConfiguration NewConf;
				NewConf.m_StartX = 0;
				NewConf.m_StartY = 0;
				NewConf.m_EndX = 0;
				NewConf.m_EndY = 0;
				int ConfigurationID = m_lConfigs.add(NewConf);
				pCurrentConf = &m_lConfigs[ConfigurationID];
				str_copy(pCurrentConf->m_aName, pLine, str_length(pLine));

				// add start run
				CRun NewRun;
				NewRun.m_AutomapCopy = true;
				int RunID = pCurrentConf->m_aRuns.add(NewRun);
				pCurrentRun = &pCurrentConf->m_aRuns[RunID];
			}
			else if(str_startswith(pLine, "NewRun"))
			{
				// add new run
				CRun NewRun;
				NewRun.m_AutomapCopy = true;
				int RunID = pCurrentConf->m_aRuns.add(NewRun);
				pCurrentRun = &pCurrentConf->m_aRuns[RunID];
			}
			else if(str_startswith(pLine, "Index") && pCurrentRun)
			{
				// new index
				int ID = 0;
				char aOrientation1[128] = "";
				char aOrientation2[128] = "";
				char aOrientation3[128] = "";

				sscanf(pLine, "Index %d %127s %127s %127s", &ID, aOrientation1, aOrientation2, aOrientation3);

				CIndexRule NewIndexRule;
				NewIndexRule.m_ID = ID;
				NewIndexRule.m_Flag = 0;
				NewIndexRule.m_RandomProbability = 1.0;
				NewIndexRule.m_DefaultRule = true;
				NewIndexRule.m_SkipEmpty = false;
				NewIndexRule.m_SkipFull = false;

				if(str_length(aOrientation1) > 0)
				{
					if(!str_comp(aOrientation1, "XFLIP"))
						NewIndexRule.m_Flag |= TILEFLAG_VFLIP;
					else if(!str_comp(aOrientation1, "YFLIP"))
						NewIndexRule.m_Flag |= TILEFLAG_HFLIP;
					else if(!str_comp(aOrientation1, "ROTATE"))
						NewIndexRule.m_Flag |= TILEFLAG_ROTATE;
				}

				if(str_length(aOrientation2) > 0)
				{
					if(!str_comp(aOrientation2, "XFLIP"))
						NewIndexRule.m_Flag |= TILEFLAG_VFLIP;
					else if(!str_comp(aOrientation2, "YFLIP"))
						NewIndexRule.m_Flag |= TILEFLAG_HFLIP;
					else if(!str_comp(aOrientation2, "ROTATE"))
						NewIndexRule.m_Flag |= TILEFLAG_ROTATE;
				}

				if(str_length(aOrientation3) > 0)
				{
					if(!str_comp(aOrientation3, "XFLIP"))
						NewIndexRule.m_Flag |= TILEFLAG_VFLIP;
					else if(!str_comp(aOrientation3, "YFLIP"))
						NewIndexRule.m_Flag |= TILEFLAG_HFLIP;
					else if(!str_comp(aOrientation3, "ROTATE"))
						NewIndexRule.m_Flag |= TILEFLAG_ROTATE;
				}

				// add the index rule object and make it current
				int IndexRuleID = pCurrentRun->m_aIndexRules.add(NewIndexRule);
				pCurrentIndex = &pCurrentRun->m_aIndexRules[IndexRuleID];
			}
			else if(str_startswith(pLine, "Pos") && pCurrentIndex)
			{
				int x = 0, y = 0;
				char aValue[128];
				int Value = CPosRule::NORULE;
				array<CIndexInfo> NewIndexList;

				sscanf(pLine, "Pos %d %d %127s", &x, &y, aValue);

				if(!str_comp(aValue, "EMPTY"))
				{
					Value = CPosRule::INDEX;
					CIndexInfo NewIndexInfo = {0, 0, false};
					NewIndexList.add(NewIndexInfo);
				}
				else if(!str_comp(aValue, "FULL"))
				{
					Value = CPosRule::NOTINDEX;
					CIndexInfo NewIndexInfo1 = {0, 0, false};
					//CIndexInfo NewIndexInfo2 = {-1, 0};
					NewIndexList.add(NewIndexInfo1);
					//NewIndexList.add(NewIndexInfo2);
				}
				else if(!str_comp(aValue, "INDEX") || !str_comp(aValue, "NOTINDEX"))
				{
					if(!str_comp(aValue, "INDEX"))
						Value = CPosRule::INDEX;
					else
						Value = CPosRule::NOTINDEX;

					int pWord = 4;
					while(true) {
						int ID = 0;
						char aOrientation1[128] = "";
						char aOrientation2[128] = "";
						char aOrientation3[128] = "";
						char aOrientation4[128] = "";
						sscanf(str_trim_words(pLine, pWord), "%d %127s %127s %127s %127s", &ID, aOrientation1, aOrientation2, aOrientation3, aOrientation4);

						CIndexInfo NewIndexInfo;
						NewIndexInfo.m_ID = ID;
						NewIndexInfo.m_Flag = 0;
						NewIndexInfo.m_TestFlag = false;

						if(!str_comp(aOrientation1, "OR")) {
							NewIndexList.add(NewIndexInfo);
							pWord += 2;
							continue;
						} else if(str_length(aOrientation1) > 0) {
							NewIndexInfo.m_TestFlag = true;
							if(!str_comp(aOrientation1, "XFLIP"))
								NewIndexInfo.m_Flag = TILEFLAG_VFLIP;
							else if(!str_comp(aOrientation1, "YFLIP"))
								NewIndexInfo.m_Flag = TILEFLAG_HFLIP;
							else if(!str_comp(aOrientation1, "ROTATE"))
								NewIndexInfo.m_Flag = TILEFLAG_ROTATE;
							else if(!str_comp(aOrientation1, "NONE"))
								NewIndexInfo.m_Flag = 0;
							else
								NewIndexInfo.m_TestFlag = false;
						} else {
							NewIndexList.add(NewIndexInfo);
							break;
						}

						if(!str_comp(aOrientation2, "OR")) {
							NewIndexList.add(NewIndexInfo);
							pWord += 3;
							continue;
						} else if(str_length(aOrientation2) > 0 && NewIndexInfo.m_Flag != 0) {
							if(!str_comp(aOrientation2, "XFLIP"))
								NewIndexInfo.m_Flag |= TILEFLAG_VFLIP;
							else if(!str_comp(aOrientation2, "YFLIP"))
								NewIndexInfo.m_Flag |= TILEFLAG_HFLIP;
							else if(!str_comp(aOrientation2, "ROTATE"))
								NewIndexInfo.m_Flag |= TILEFLAG_ROTATE;
						} else {
							NewIndexList.add(NewIndexInfo);
							break;
						}

						if(!str_comp(aOrientation3, "OR")) {
							NewIndexList.add(NewIndexInfo);
							pWord += 4;
							continue;
						} else if(str_length(aOrientation3) > 0 && NewIndexInfo.m_Flag != 0) {
							if(!str_comp(aOrientation3, "XFLIP"))
								NewIndexInfo.m_Flag |= TILEFLAG_VFLIP;
							else if(!str_comp(aOrientation3, "YFLIP"))
								NewIndexInfo.m_Flag |= TILEFLAG_HFLIP;
							else if(!str_comp(aOrientation3, "ROTATE"))
								NewIndexInfo.m_Flag |= TILEFLAG_ROTATE;
						} else {
							NewIndexList.add(NewIndexInfo);
							break;
						}

						if(!str_comp(aOrientation4, "OR")) {
							NewIndexList.add(NewIndexInfo);
							pWord += 5;
							continue;
						} else {
							NewIndexList.add(NewIndexInfo);
							break;
						}
					}
				}

				if(Value != CPosRule::NORULE) {
					CPosRule NewPosRule = {x, y, Value, NewIndexList};
					pCurrentIndex->m_aRules.add(NewPosRule);

					pCurrentConf->m_StartX = min(pCurrentConf->m_StartX, NewPosRule.m_X);
					pCurrentConf->m_StartY = min(pCurrentConf->m_StartY, NewPosRule.m_Y);
					pCurrentConf->m_EndX = max(pCurrentConf->m_EndX, NewPosRule.m_X);
					pCurrentConf->m_EndY = max(pCurrentConf->m_EndY, NewPosRule.m_Y);

					if(x == 0 && y == 0) {
						for(int i = 0; i < NewIndexList.size(); ++i) 
						{
							if(Value == CPosRule::INDEX && NewIndexList[i].m_ID == 0)
								pCurrentIndex->m_SkipFull = true;
							else
								pCurrentIndex->m_SkipEmpty = true;
						}
					}
				}
			}
			else if(str_startswith(pLine, "Random") && pCurrentIndex)
			{
				float Value;
				char Specifier = ' ';
				sscanf(pLine, "Random %f%c", &Value, &Specifier);
				if(Specifier == '%')
				{
					pCurrentIndex->m_RandomProbability = Value / 100.0;
				}
				else
				{
					pCurrentIndex->m_RandomProbability = 1.0 / Value;
				}
			}
			else if(str_startswith(pLine, "NoDefaultRule") && pCurrentIndex)
			{
				pCurrentIndex->m_DefaultRule = false;
			}
			else if(!str_comp_num(pLine, "NoLayerCopy", 11) && pCurrentRun)
			{
				pCurrentRun->m_AutomapCopy = false;
			}
		}
	}

	// add default rule for Pos 0 0 if there is none
	for (int g = 0; g < m_lConfigs.size(); ++g)
	{
		for (int h = 0; h < m_lConfigs[g].m_aRuns.size(); ++h)
		{
			for(int i = 0; i < m_lConfigs[g].m_aRuns[h].m_aIndexRules.size(); ++i)
			{
				CIndexRule *pIndexRule = &m_lConfigs[g].m_aRuns[h].m_aIndexRules[i];
				bool Found = false;
				for(int j = 0; j < pIndexRule->m_aRules.size(); ++j)
				{
					CPosRule *pRule = &pIndexRule->m_aRules[j];
					if(pRule && pRule->m_X == 0 && pRule->m_Y == 0)
					{
						Found = true;
						break;
					}
				}
				if(!Found && pIndexRule->m_DefaultRule)
				{
					array<CIndexInfo> NewIndexList;
					CIndexInfo NewIndexInfo = {0, 0, false};
					NewIndexList.add(NewIndexInfo);
					CPosRule NewPosRule = {0, 0, CPosRule::NOTINDEX, NewIndexList};
					pIndexRule->m_aRules.add(NewPosRule);
					
					pIndexRule->m_SkipEmpty = true;
					pIndexRule->m_SkipFull = false;
				}
				if(pIndexRule->m_SkipEmpty && pIndexRule->m_SkipFull)
				{
					pIndexRule->m_SkipFull = false;
				}
			}
		}
	}

	io_close(RulesFile);

	str_format(aBuf, sizeof(aBuf),"loaded %s", aPath);
	m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", aBuf);

	m_FileLoaded = true;
}
Example #28
0
int CSound::LoadWV(const char *pFilename)
{
	CSample *pSample;
	int SampleID = -1;
	char aError[100];
	WavpackContext *pContext;

	// don't waste memory on sound when we are stress testing
	if(g_Config.m_DbgStress)
		return -1;

	// no need to load sound when we are running with no sound
	if(!m_SoundEnabled)
		return 1;

	if(!m_pStorage)
		return -1;

	ms_File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);
	if(!ms_File)
	{
		dbg_msg("sound/wv", "failed to open file. filename='%s'", pFilename);
		return -1;
	}

	SampleID = AllocID();
	if(SampleID < 0)
		return -1;
	pSample = &m_aSamples[SampleID];

	pContext = WavpackOpenFileInput(ReadData, aError);
	if (pContext)
	{
		int m_aSamples = WavpackGetNumSamples(pContext);
		int BitsPerSample = WavpackGetBitsPerSample(pContext);
		unsigned int SampleRate = WavpackGetSampleRate(pContext);
		int m_aChannels = WavpackGetNumChannels(pContext);
		int *pData;
		int *pSrc;
		short *pDst;
		int i;

		pSample->m_Channels = m_aChannels;
		pSample->m_Rate = SampleRate;

		if(pSample->m_Channels > 2)
		{
			dbg_msg("sound/wv", "file is not mono or stereo. filename='%s'", pFilename);
			return -1;
		}

		/*
		if(snd->rate != 44100)
		{
			dbg_msg("sound/wv", "file is %d Hz, not 44100 Hz. filename='%s'", snd->rate, filename);
			return -1;
		}*/

		if(BitsPerSample != 16)
		{
			dbg_msg("sound/wv", "bps is %d, not 16, filname='%s'", BitsPerSample, pFilename);
			return -1;
		}

		pData = (int *)mem_alloc(4*m_aSamples*m_aChannels, 1);
		WavpackUnpackSamples(pContext, pData, m_aSamples); // TODO: check return value
		pSrc = pData;

		pSample->m_pData = (short *)mem_alloc(2*m_aSamples*m_aChannels, 1);
		pDst = pSample->m_pData;

		for (i = 0; i < m_aSamples*m_aChannels; i++)
			*pDst++ = (short)*pSrc++;

		mem_free(pData);

		pSample->m_NumFrames = m_aSamples;
		pSample->m_LoopStart = -1;
		pSample->m_LoopEnd = -1;
		pSample->m_PausedAt = 0;
	}
	else
	{
		dbg_msg("sound/wv", "failed to open %s: %s", pFilename, aError);
	}

	io_close(ms_File);
	ms_File = NULL;

	if(g_Config.m_Debug)
		dbg_msg("sound/wv", "loaded %s", pFilename);

	RateConvert(SampleID);
	return SampleID;
}
Example #29
0
int CDataFileWriter::Finish()
{
	if(!m_File) return 1;

	int ItemSize = 0;
	int TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize;
	int DataSize = 0;
	CDatafileHeader Header;

	// we should now write this file!
	if(DEBUG)
		dbg_msg("datafile", "writing");

	// calculate sizes
	for(int i = 0; i < m_NumItems; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "item=%d size=%d (%d)", i, m_aItems[i].m_Size, m_aItems[i].m_Size+sizeof(CDatafileItem));
		ItemSize += m_aItems[i].m_Size + sizeof(CDatafileItem);
	}


	for(int i = 0; i < m_NumDatas; i++)
		DataSize += m_aDatas[i].m_CompressedSize;

	// calculate the complete size
	TypesSize = m_NumItemTypes*sizeof(CDatafileItemType);
	HeaderSize = sizeof(CDatafileHeader);
	OffsetSize = (m_NumItems + m_NumDatas + m_NumDatas) * sizeof(int); // ItemOffsets, DataOffsets, DataUncompressedSizes
	FileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize;
	SwapSize = FileSize - DataSize;

	(void)SwapSize;

	if(DEBUG)
		dbg_msg("datafile", "num_m_aItemTypes=%d TypesSize=%d m_aItemsize=%d DataSize=%d", m_NumItemTypes, TypesSize, ItemSize, DataSize);

	// construct Header
	{
		Header.m_aID[0] = 'D';
		Header.m_aID[1] = 'A';
		Header.m_aID[2] = 'T';
		Header.m_aID[3] = 'A';
		Header.m_Version = 4;
		Header.m_Size = FileSize - 16;
		Header.m_Swaplen = SwapSize - 16;
		Header.m_NumItemTypes = m_NumItemTypes;
		Header.m_NumItems = m_NumItems;
		Header.m_NumRawData = m_NumDatas;
		Header.m_ItemSize = ItemSize;
		Header.m_DataSize = DataSize;

		// write Header
		if(DEBUG)
			dbg_msg("datafile", "HeaderSize=%d", sizeof(Header));
#if defined(CONF_ARCH_ENDIAN_BIG)
		swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int));
#endif
		io_write(m_File, &Header, sizeof(Header));
	}

	// write types
	for(int i = 0, Count = 0; i < 0xffff; i++)
	{
		if(m_aItemTypes[i].m_Num)
		{
			// write info
			CDatafileItemType Info;
			Info.m_Type = i;
			Info.m_Start = Count;
			Info.m_Num = m_aItemTypes[i].m_Num;
			if(DEBUG)
				dbg_msg("datafile", "writing type=%x start=%d num=%d", Info.m_Type, Info.m_Start, Info.m_Num);
#if defined(CONF_ARCH_ENDIAN_BIG)
			swap_endian(&Info, sizeof(int), sizeof(CDatafileItemType)/sizeof(int));
#endif
			io_write(m_File, &Info, sizeof(Info));
			Count += m_aItemTypes[i].m_Num;
		}
	}

	// write item offsets
	for(int i = 0, Offset = 0; i < 0xffff; i++)
	{
		if(m_aItemTypes[i].m_Num)
		{
			// write all m_aItems in of this type
			int k = m_aItemTypes[i].m_First;
			while(k != -1)
			{
				if(DEBUG)
					dbg_msg("datafile", "writing item offset num=%d offset=%d", k, Offset);
				int Temp = Offset;
#if defined(CONF_ARCH_ENDIAN_BIG)
				swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int));
#endif
				io_write(m_File, &Temp, sizeof(Temp));
				Offset += m_aItems[k].m_Size + sizeof(CDatafileItem);

				// next
				k = m_aItems[k].m_Next;
			}
		}
	}

	// write data offsets
	for(int i = 0, Offset = 0; i < m_NumDatas; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "writing data offset num=%d offset=%d", i, Offset);
		int Temp = Offset;
#if defined(CONF_ARCH_ENDIAN_BIG)
		swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int));
#endif
		io_write(m_File, &Temp, sizeof(Temp));
		Offset += m_aDatas[i].m_CompressedSize;
	}

	// write data uncompressed sizes
	for(int i = 0; i < m_NumDatas; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "writing data uncompressed size num=%d size=%d", i, m_aDatas[i].m_UncompressedSize);
		int UncompressedSize = m_aDatas[i].m_UncompressedSize;
#if defined(CONF_ARCH_ENDIAN_BIG)
		swap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize)/sizeof(int));
#endif
		io_write(m_File, &UncompressedSize, sizeof(UncompressedSize));
	}

	// write m_aItems
	for(int i = 0; i < 0xffff; i++)
	{
		if(m_aItemTypes[i].m_Num)
		{
			// write all m_aItems in of this type
			int k = m_aItemTypes[i].m_First;
			while(k != -1)
			{
				CDatafileItem Item;
				Item.m_TypeAndID = (i<<16)|m_aItems[k].m_ID;
				Item.m_Size = m_aItems[k].m_Size;
				if(DEBUG)
					dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_aItems[k].m_ID, m_aItems[k].m_Size);

#if defined(CONF_ARCH_ENDIAN_BIG)
				swap_endian(&Item, sizeof(int), sizeof(Item)/sizeof(int));
				swap_endian(m_aItems[k].m_pData, sizeof(int), m_aItems[k].m_Size/sizeof(int));
#endif
				io_write(m_File, &Item, sizeof(Item));
				io_write(m_File, m_aItems[k].m_pData, m_aItems[k].m_Size);

				// next
				k = m_aItems[k].m_Next;
			}
		}
	}

	// write data
	for(int i = 0; i < m_NumDatas; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "writing data id=%d size=%d", i, m_aDatas[i].m_CompressedSize);
		io_write(m_File, m_aDatas[i].m_pCompressedData, m_aDatas[i].m_CompressedSize);
	}

	// free data
	for(int i = 0; i < m_NumItems; i++)
		mem_free(m_aItems[i].m_pData);
	for(int i = 0; i < m_NumDatas; ++i)
		mem_free(m_aDatas[i].m_pCompressedData);

	io_close(m_File);
	m_File = 0;

	if(DEBUG)
		dbg_msg("datafile", "done");
	return 0;
}
Example #30
0
int
main(int argc, char* argv[]) {
  int s = socket_tcp6();
  uint32 scope_id;
  char ip[16];
  uint16 port;
  char hisip[16];
  uint16 hisport;
  uint32 hisscope_id;
  static char seed[128];
  static stralloc fqdn;
  static stralloc out;

  if(argc != 4) {
  usage:
    buffer_putsflush(buffer_2,
                     "usage: proxy myip myport hisip hisport\n"
                     "\n"
                     "e.g.: proxy 0 119 news.fu-berlin.de 119\n");
    return 0;
  }

  if(argv[1][scan_ip6if(argv[1], ip, &scope_id)]) {
    if(str_equal(argv[1], "0")) {
      byte_zero(ip, 16);
      scope_id = 0;
    } else
      goto usage;
  }
  if(argv[2][scan_ushort(argv[2], &port)])
    goto usage;
  if(argv[3][scan_ip6if(argv[3], hisip, &hisscope_id)]) {
    dns_random_init(seed);
    if(!stralloc_copys(&fqdn, argv[3]))
      goto nomem;
    if(dns_ip4(&out, &fqdn) == -1) {
      buffer_puts(buffer_2, "unable to find IP address for ");
      buffer_puts(buffer_2, argv[3]);
      buffer_puts(buffer_2, ": ");
      buffer_puterror(buffer_2);
      buffer_putnlflush(buffer_2);
      return 111;
    }
  } else if(!stralloc_catb(&out, hisip, 16)) {
  nomem:
    buffer_putsflush(buffer_2, "out of memory\n");
    return 111;
  }
  if(argv[4][scan_ushort(argv[4], &hisport)])
    goto usage;

  if(socket_bind6_reuse(s, ip, port, scope_id) == -1) {
    buffer_puts(buffer_2, "socket_bind6_reuse: ");
    buffer_puterror(buffer_2);
    buffer_putnlflush(buffer_2);
    return 111;
  }
  if(socket_listen(s, 16) == -1) {
    buffer_puts(buffer_2, "socket_listen: ");
    buffer_puterror(buffer_2);
    buffer_putnlflush(buffer_2);
    return 111;
  }
  if(!io_fd(s)) {
    buffer_puts(buffer_2, "io_fd: ");
    buffer_puterror(buffer_2);
    buffer_putnlflush(buffer_2);
    return 111;
  }
  io_wantread(s);
  for(;;) {
    int64 i;
    io_wait();
    while((i = io_canread()) != -1) {
      if(i == s) {
        /* the read event is on the server socket */
        /* that means it's an incoming connection */
        int n;
        while((n = socket_accept6(s, ip, &port, &scope_id)) != -1) {
          int x = socket_tcp6();
          if(x == -1) {
            buffer_puts(buffer_2, "socket_tcp6 failed: ");
          fail:
            buffer_puterror(buffer_2);
            buffer_putnlflush(buffer_2);
            io_close(n);
          } else {
            struct state* s = malloc(sizeof(struct state));
            if(!s)
              goto closefail;
            s->a = n;
            s->b = x;
            s->connected = 0;
            s->done = s->todo = 0;
            s->dir = UNDECIDED;
            io_nonblock(x);
            socket_connect6(x, out.s, hisport, hisscope_id);
            if(!io_fd(x) || !io_fd(n)) {
              buffer_puts(buffer_2, "io_fd failed: ");
            closefail:
              free(s);
              io_close(x);
              goto fail;
            }
            io_setcookie(x, s);
            io_setcookie(n, s);
            io_wantwrite(x);
          }
        }
        if(errno != EAGAIN) {
          buffer_puts(buffer_2, "socket_accept6 failed: ");
          buffer_puterror(buffer_2);
          buffer_putnlflush(buffer_2);
        }
      } else {
        /* read event on an established connection */
        struct state* s = io_getcookie(i);
        int l = io_tryread(i, s->buf, sizeof(s->buf));
        if(l == -1) {
          buffer_puts(buffer_2, "io_tryread(");
          buffer_putulong(buffer_2, i);
          buffer_puts(buffer_2, "): ");
          buffer_puterror(buffer_2);
          buffer_putnlflush(buffer_2);
          io_close(s->a);
          io_close(s->b);
        } else if(l == 0) {
          buffer_puts(buffer_2, "eof on fd #");
          buffer_putulong(buffer_2, i);
          buffer_putnlflush(buffer_2);
          io_close(i);
        } else {
          int r;
          switch(r = io_trywrite(i, s->buf, l)) {
            case -1:
              buffer_puts(buffer_2, "io_tryread(");
              buffer_putulong(buffer_2, i);
              buffer_puts(buffer_2, "): ");
              buffer_puterror(buffer_2);
              buffer_putnlflush(buffer_2);
              io_close(i);
              break;
            case 0:
              buffer_puts(buffer_2, "write eof on fd #");
              buffer_putulong(buffer_2, i);
              buffer_putnlflush(buffer_2);
              io_close(i);
            default:
              if(r != l) {
                buffer_puts(buffer_2, "short write on fd #");
                buffer_putulong(buffer_2, i);
                buffer_puts(buffer_2, ": wrote ");
                buffer_putulong(buffer_2, r);
                buffer_puts(buffer_2, ", wanted to write ");
                buffer_putulong(buffer_2, l);
                buffer_putsflush(buffer_2, ").\n");
              }
          }
        }
      }
    }
  }
  return 0;
}