Пример #1
0
/**
 * on error the function returns -1 and sets value to EMPTY_PLACER
 * on success the function returns 0 and stores the token in the placer pointed at by value
 * if the end is hit, then the function returns 1, and places any remaining data in value
 */
int tok_pop(tok_state_t *state, placer_t *value) {

	char *startPosition;

	// We can't search NULL pointers or empty strings.
	if (!value || !state || !state->position) {

		if (value) {
			*value = pl_null();
		}

		return -1;
	}

	// Handle situations where there is no more data.
	if (!(state->remaining)) {
		*value = pl_null();
		return 1;
	}


	// Handle situations where the pointer is already at the token.
	if (*(state->position) == state->token) {

		(state->position)++;
		(state->remaining)--;
		*value = pl_null();

		if (!(state->remaining)) {
			return 1;
		}

		return 0;
	}

	startPosition = state->position;

	while (*(state->position) != state->token && (state->remaining)) {
		(state->position)++;
		(state->remaining)--;
	}

	// If we hit the token on the first character, return NULL
	if ((startPosition) == state->position) {
		*value = pl_null();
	} else {
		*value = pl_init(startPosition, state->position - startPosition);
	}

	// We hit the end of the block
	if (!(state->remaining)) {
		return 1;
	}

	// Advance to the next character for next time.
	(state->position)++;
	(state->remaining)--;

	return 0;
}
Пример #2
0
/**
 * @brief	Get a placer pointing to a mime header in a mime part.
 * @param	part	a managed string containing the mime part text to be parsed.
 * @return	a placer pointing to the mime header at the start of the specified mime part.
 */
placer_t mail_mime_header(stringer_t *part) {

	chr_t *stream;
	size_t length;
	int_t header = 0;

	length = st_length_get(part);
	stream = st_data_get(part);

	for (size_t i = 0; i < length && header != 3; i++) {

		if (header == 0 && *stream == '\n') {
			header++;
		}
		else if (header == 1 && *stream == '\n') {
			header += 2;
		}
		else if (header == 1 && *stream == '\r') {
			header++;
		}
		else if (header == 2 && *stream == '\n') {
			header++;
		}
		else if (header != 0) {
			header = 0;
		}

		stream++;
	}

	return pl_init(st_data_get(part), stream - st_char_get(part));
}
Пример #3
0
/**
 * @brief	Get a placer pointing to the specified line ('\n' delimited) of content in a data buffer.
 * @param	block	a pointer to the block of data to be scanned.
 * @param	length	the length, in bytes, of the specified data buffer.
 * @param	number	the zero-based index of the line to be retrieved from the buffer.
 * @return	a null placer on failure, or a placer pointing to the specified line on success.
 */
placer_t line_pl_bl(char *block, size_t length, uint64_t number) {

	char *start;

	// We can't search NULL pointers or empty blocks.
	if (mm_empty(block, length)) {
		log_pedantic("Passed an invalid parameter.");
		return pl_null();
	}

	// Keep advancing till we reach the requested line, or the end of the block.
	while (number && length--) {

		if (*block++ == '\n') {
			number--;
		}

	}

	// If we hit the end of the string before finding the requested line, return NULL.
	if (!length || number) {
		return pl_null();
	}

	// Advance through until we reach the next new-line character.
	start = block;

	while (length-- && *block++ != '\n');

	if (*(block - 1) != '\n') {
		return pl_null();
	}

	return pl_init(start, block - start);
}
Пример #4
0
void
sim_init(void)
{
  pl_init();

  sim_spacecraft_control_init();

  // Set log level, need to do that here
  const char *levStr = NULL;
  config_get_str_def("openorbit/sys/log-level", &levStr, "info");
  log_set_level(log_get_lev_from_str(levStr));

  // Load and run initialisation script
  scripting_init();

  if (!scripting_run_file("script/init.py")) {
    log_fatal("script/init.py missing");
  }

  sim_init_graphics();

  float freq;
  config_get_float_def("openorbit/sim/freq", &freq, 20.0); // Read in Hz
  gSIM_state.stepSize = 1.0 / freq; // Period in s
  
  // Setup IO-tables, must be done after joystick system has been initialised
  io_init();

  gSIM_state.world = sim_load_world(sim_get_scene(), "data/solsystem.hrml");
  pl_time_set(sim_time_get_jd());


  sim_spacecraft_t *sc = sim_new_spacecraft("Mercury", "Mercury I");
  sim_spacecraft_set_sys_and_coords(sc, "Earth",
                      0.0 /*longitude*/,
                      0.0 /*latitude*/,
                      250.0e3 /*altitude*/);
  sim_set_spacecraft(sc);

  sg_camera_t *cam = sg_scene_get_cam(sc->scene);
  sim_stage_t *stage = ARRAY_ELEM(sc->stages, 1);
  sg_camera_track_object(cam, stage->sgobj);
  sg_camera_follow_object(cam, stage->sgobj);
  sg_camera_set_follow_offset(cam, vd3_set(0.0, 0.0, -150.0e9));

  simMfdInitAll(sim_get_main_viewport());

  sim_init_plugins();

  if (!scripting_run_file("script/postinit.py")) {
    log_fatal("script/postinit.py missing");
  }

  sim_setup_menus(&gSIM_state);
}
Пример #5
0
/**
 * @brief	Retrieve a specified token from a null-terminated string.
 * @param	string		a pointer to the null-terminated string to be tokenized.
 * @param	length		the maximum number of characters to be scanned from the input string.
 * @param	token		the token character that will be used to split the string.
 * @param	fragment	the zero-indexed token number to be extracted from the string.
 * @param	value		a pointer to a placer that will receive the value of the extracted token on success, or pl_null() on failure.
 * @return	-1 on failure, 0 on success, or 1 if the token was extracted successfully, but was the last one in the string.
 */
int tok_get_ns(char *string, size_t length, char token, uint64_t fragment, placer_t *value) {

	char *start;

#ifdef MAGMA_PEDANTIC
	if (!string) log_pedantic("Attempted token extraction from a NULL string buffer.");
	else if (!length) log_pedantic("Attempted token extraction from an empty string.");
#endif

	// We can't search NULL pointers or empty strings.
	if (!value || mm_empty(string, length)) {

		if (value) {
			*value = pl_null();
		}

		return -1;
	}

	while (fragment && length--) {

		if (*string++ == token) {
			fragment--;
		}

	}

	if (fragment) {
		*value = pl_null();
		return 1;
	}

	start = string;

	while (length && *string != token) {
		string++;
		length--;
	}

	// If we hit the token on the first character, return NULL
	if (start == string) {
		*value = pl_null();
	}
	else {
		*value = pl_init(start, string - start);
	}

	// We hit the end of the string
	if (!length) {
		return 1;
	}

	return 0;
}
Пример #6
0
extern void j1939_init(void)
{
    debug_init();
    fifo_init();

    al_init();
    dl_init();
    pl_init();

    return;
}
Пример #7
0
static Polygon * 
pl_check_pointer(Polygon ** pl_pt){
	assert(pl_pt);
	
	Polygon * result= *pl_pt;
	
	if (!result){
		result= *pl_pt= pl_init(10);
	}
	
	return result;
}
Пример #8
0
placer_t imap_parse_address_breaker(stringer_t *address, uint32_t part) {

	size_t length;
	int_t status = 0;
	uint32_t position = 0;
	placer_t output = pl_null();
	chr_t *holder, *start = NULL, *end = NULL;

	if (address == NULL) {
		return pl_null();
	}

	length = st_length_get(address);
	holder = st_char_get(address);

	while (length > 0 && end == NULL) {

		if (position == part) {
			start = holder;
			position++;
		}

		// Inside quotes, nothing counts.
		if (status == 0 && *holder == '\"') {
			status = 1;
		}
		else if (status == 1 && *holder == '\"') {
			status = 0;
		}
		// Outside quotes, and we hit the break character.
		else if (status == 0 && position > part && *holder == ',') {
			end = holder;
		}
		else if (status == 0 && position < part && *holder == ',') {
			position++;
		}

		length--;
		holder++;
	}

	// If we hit the end.
	if (end == NULL) {
		end = holder;
	}

	if (start != NULL && end != NULL) {
		output = pl_init(start, end - start);
	}

	return output;
}
Пример #9
0
/**
 * @brief	Count the number of times a string token is found in a specified block of memory.
 * @param	block	a pointer to a block of memory to be scanned.
 * @param	length	the length, in bytes, of the block of memory to be scanned.
 * @param	token	a pointer to the string token being used to split the input data.
 * @param	toklen	the length, in bytes, of the specified token.
 * @return	the number of times the string token was found in the block of memory, or 0 on failure.
 */
uint64_t str_tok_get_count_bl(void *block, size_t length, chr_t *token, size_t toklen) {

	uint64_t count = 0;
	placer_t haystack, needle;
	size_t hptr, skipped = 0;

	// We can't search NULL pointers or empty strings.
	if (mm_empty(block, length) || mm_empty(token, toklen)) {
		return 0;
	}

	haystack = pl_init(block, length);
	needle = pl_init(token, toklen);

	while ((skipped < length) && st_search_cs(&haystack, &needle, &hptr)) {
		skipped += pl_length_get (needle) + hptr;
		haystack = pl_init((char *) block + skipped, length-skipped);
		count++;
	}

	return count;
}
Пример #10
0
// QUESTION: Should this function always return 1??
int_t mail_mime_update(mail_message_t *message) {

	placer_t part;

	if (message->mime) {
		mail_mime_free(message->mime);
	}

	part = pl_init(st_char_get(message->text), st_length_get(message->text));
	message->mime = mail_mime_part(&part, 1);

	return 1;
}
Пример #11
0
/**
 * @brief	Retrieve a specified string-split token from a null-terminated string.
 * @param	block		a pointer to the block of memory to be tokenized.
 * @param	length		the maximum number of characters to be scanned from the input data.
 * @param	token		the token string that will be used to split the data.
 * @param	toklen		the length, in bytes, of the token string.
 * @param	fragment	the zero-indexed token number to be extracted from the data.
 * @param	value		a pointer to a placer that will receive the value of the extracted token on success, or pl_null() on failure.
 * @return	-1 on failure, 0 on success, or 1 if the token was extracted successfully, but was the last one in the string.
 */
int str_tok_get_bl(char *block, size_t length, chr_t *token, size_t toklen, uint64_t fragment, placer_t *value) {

	placer_t haystack, needle;
	size_t hptr, skipped = 0;
	bool_t found;

	// We can't search NULL pointers or empty strings.
	if (!value || mm_empty(block, length) || mm_empty(token, toklen)) {
		*value = pl_null();
		return -1;
	}

	haystack = pl_init(block, length);
	needle = pl_init(token, toklen);

	while (fragment) {

		if (!(found = st_search_cs(&haystack, &needle, &hptr))) {
			*value = pl_null();
			return -1;
		}

		// Haystack becomes the entire block after the token.
		skipped += pl_length_get (needle) + hptr;
		haystack = pl_init(pl_char_get(haystack) + skipped, length-skipped);
		fragment--;
	}

	// If no more tokens are present, return everything we have left
	if (!st_search_cs(&haystack, &needle, &hptr)) {
		*value = haystack;
		return 1;
	}

	*value = pl_init(pl_char_get(haystack), hptr);

	return 0;
}
Пример #12
0
void pc_addpg(struct pcache *pc, void *page, size_t pgsiz)
{
	struct pc_pool *pcp;

	abort_unless(pc);
	abort_unless(page);
	abort_unless(pgsiz >= sizeof(union pc_pool_u) + pl_isiz(pc->asiz, -1));

	pcp = page;
	pl_init(&pcp->pool, pc->asiz, -1, (char *)pcp + sizeof(union pc_pool_u),
		pgsiz - sizeof(union pc_pool_u));
	pcp->cache = pc;
	l_ins(&pc->avail, &pcp->entry);
	pc->npools += 1;
}
Пример #13
0
int main()
{
    // decomp
    plugin_ldpath(".");

    void *pl = plugin_load("libdecomp.so");

    if (!pl)
    {
        printf("missing plugin\n");
        return 1;
    }

    decomp3f_init_f pl_init = (decomp3f_init_f)plugin_fn(pl, DECOMP3F_INIT_F_SYM);
    decomp3f_make_f pl_make = (decomp3f_make_f)plugin_fn(pl, DECOMP3F_MAKE_F_SYM);
    decomp3f_clear_f pl_clear = (decomp3f_clear_f)plugin_fn(pl, DECOMP3F_CLEAR_F_SYM);

    struct decomp3f_s d;

    struct decompmesh3f_s dm;
    load_mesh(&dm, "../data/mushroom.off");

    pl_init(&d);

    uint64_t start = timer_usec();

    pl_make(&d, &dm);

    uint64_t end = timer_usec();

    printf("decomposition took %lu usecs; sub-meshes: %d\n", static_cast<unsigned long>(end - start), static_cast<int>(d.ms));

    pl_clear(&d);

    plugin_unload(pl);

    free(dm.f);
    free(dm.v);

    return 0;
}
Пример #14
0
int main(int argc, char **argv)
{
	char file[MAXPATHLEN] = "";
	char path[MAXPATHLEN];
	const char *cdfile = NULL;
	int loadst = 0;
	int i;

	emu_core_preinit();
	ChangeWorkingDirectory("c");

	strcpy(Config.BiosDir, "/home/user/MyDocs");
	strcpy(Config.PluginsDir, "/opt/maemo/usr/games/plugins");
	snprintf(Config.PatchesDir, sizeof(Config.PatchesDir), "/opt/maemo/usr/games" PATCHES_DIR);
	Config.PsxAuto = 1;

	g_menuscreen_w = 800;
	g_menuscreen_h = 480;

	pl_init();

	emu_core_init();

	// read command line options
	for (i = 1; i < argc; i++) {
		     if (!strcmp(argv[i], "-psxout")) Config.PsxOut = 1;
		else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
		else if (!strcmp(argv[i], "-cdfile")) {
			char isofilename[MAXPATHLEN];
			if (i+1 >= argc) break;
			strncpy(isofilename, argv[++i], MAXPATHLEN);
			if (isofilename[0] != '/') {
				getcwd(path, MAXPATHLEN);
				if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
					strcat(path, "/");
					strcat(path, isofilename);
					strcpy(isofilename, path);
				} else
					isofilename[0] = 0;
			}
			cdfile = isofilename;
		}
		else if (!strcmp(argv[i],"-frameskip")) {
			int tv_reg = atol(argv[++i]);
			if (tv_reg > 0)
				pl_rearmed_cbs.frameskip = -1;
		}
		else if (!strcmp(argv[i],"-fullscreen"))		g_maemo_opts |= 2;
		else if (!strcmp(argv[i],"-accel"))				g_maemo_opts |= 4;
		else if (!strcmp(argv[i],"-nosound"))		strcpy(Config.Spu, "spunull.so");
		else if (!strcmp(argv[i], "-bdir"))			sprintf(Config.BiosDir, "%s", argv[++i]);
		else if (!strcmp(argv[i], "-bios"))			sprintf(Config.Bios, "%s", argv[++i]);
		else if (!strcmp(argv[i], "-gles"))			strcpy(Config.Gpu, "gpuGLES.so");
		else if (!strcmp(argv[i], "-cdda"))		Config.Cdda = 1;
		else if (!strcmp(argv[i], "-xa"))		Config.Xa = 1;
		else if (!strcmp(argv[i], "-rcnt"))		Config.RCntFix = 1 ;
		else if (!strcmp(argv[i], "-sio"))		Config.Sio = 1;
		else if (!strcmp(argv[i], "-spuirq"))	Config.SpuIrq = 1;
		else if (!strcmp(argv[i], "-vsync"))	Config.VSyncWA = 1;
	}

	hildon_init(&argc, &argv);
	
	if (cdfile) {
		set_cd_image(cdfile);
		strcpy(file_name, strrchr(cdfile,'/'));
	}

	if (LoadPlugins() == -1) {
		SysMessage("Failed loading plugins!");
		return 1;
	}

	if (OpenPlugins() == -1) {
		return 1;
	}
	plugin_call_rearmed_cbs();

	CheckCdrom();
	SysReset();

	if (file[0] != '\0') {
		if (Load(file) != -1)
			ready_to_go = 1;
	} else {
		if (cdfile) {
			if (LoadCdrom() == -1) {
				ClosePlugins();
				printf(_("Could not load CD-ROM!\n"));
				return -1;
			}
			emu_on_new_cd(0);
			ready_to_go = 1;
		}
	}

	if (!ready_to_go) {
		printf ("something goes wrong, maybe you forgot -cdfile ? \n");
		return 1;
	}

	// If a state has been specified, then load that
	if (loadst) {
		int ret = emu_load_state(loadst - 1);
		printf("%s state %d\n", ret ? "failed to load" : "loaded", loadst);
	}

	maemo_init(&argc, &argv);

	if (GPU_open != NULL) {
		int ret = GPU_open(&gpuDisp, "PCSX", NULL);
		if (ret)
			fprintf(stderr, "Warning: GPU_open returned %d\n", ret);
	}

	dfinput_activate();
	pl_timing_prepare(Config.PsxType);

	while (1)
	{
		stop = 0;
		emu_action = SACTION_NONE;

		psxCpu->Execute();
		if (emu_action != SACTION_NONE)
			do_emu_action();
	}

	return 0;
}
Пример #15
0
/**
 * @brief	Parse a block of data into a mail mime object.
 * @note	By parsing the specified mime part, this function fills in the content type and encoding of the resulting mail mime object.
 * 			If the message is multipart, the boundary string is determined and then used to split the body into children;
 * 			then each child part is passed to mail_mime_part() to be parsed likewise, recursively.
 * @param	part		a managed string containing the mime part data to be parsed.
 * @param	recursion	an incremented recursion level tracker for calling this function, to prevent an overflow from occurring.
 * @return	NULL on failure or a pointer to a newly allocated and updated mail mime object parsed from the part data on success.
 */
mail_mime_t * mail_mime_part(stringer_t *part, uint32_t recursion) {

	array_t *holder;
	size_t elements, increment;
	mail_mime_t *result, *subpart;

	// Recursion limiter.
	if (recursion >= MAIL_MIME_RECURSION_LIMIT) {
		log_pedantic("Recursion limit hit.");
		return NULL;
	}

	if (st_empty(part)) {
		log_pedantic("Passed an empty placer_t.");
		return NULL;
	}

	if (!(result = mm_alloc(sizeof(mail_mime_t)))) {
		log_pedantic("Could not allocate %zu bytes for the MIME structure.", sizeof(mail_mime_t));
		return NULL;
	}

	// Store the entire part, and figure out the length of the header.
	result->entire = pl_init(st_data_get(part), st_length_get(part));
	result->header = mail_mime_header(part);

	// Check to make sure the header doesn't take up the entire part.
	if (st_length_get(&(result->header)) != st_length_get(part)) {
		result->body = pl_init(st_char_get(part) + st_length_get(&(result->header)), st_length_get(part) - st_length_get(&(result->header)));
	}

	// Determine the content type.
	result->type = mail_mime_type(result->header);
	result->encoding = mail_mime_encoding(result->header);

	// If were dealing with a multipart message, get the boundary.
	if ((result->type == MESSAGE_TYPE_MULTI_ALTERNATIVE || result->type == MESSAGE_TYPE_MULTI_MIXED || result->type == MESSAGE_TYPE_MULTI_RELATED ||
		result->type == MESSAGE_TYPE_MULTI_RFC822 || result->type == MESSAGE_TYPE_MULTI_UNKOWN) && (result->boundary = mail_mime_boundary(result->header))) {

		// Get an array of message parts.
		if ((holder = mail_mime_split(result->body, result->boundary)) && (elements = ar_length_get(holder))) {

			if ((result->children = ar_alloc(elements))) {

				for (increment = 0; increment < elements; increment++) {

					if ((subpart = mail_mime_part(ar_field_st(holder, increment), recursion + 1))) {

						if (ar_append(&(result->children), ARRAY_TYPE_POINTER, subpart) != 1) {
							mail_mime_free(subpart);
						}

					}

				}

			}

		}

		if (holder) {
			ar_free(holder);
		}

	}

	return result;
}
Пример #16
0
/**
 * @brief	Get a placer pointing to the specified child inside a MIME body.
 * @param	body		a placer containing the body text to be parsed.
 * @param	boundary	a pointer to a managed string containing the boundary string to split the MIME content.
 * @param	child		the zero-based index of the MIME child to be located in the body text.
 * @return	pl_null() on failure, or a placer containing the specified MIME child on success.
 */
placer_t mail_mime_child(placer_t body, stringer_t *boundary, uint32_t child) {

	uint32_t result = 0;
	chr_t *start, *stream, *bounddata;
	size_t increment = 0, length, boundlen;

	if (pl_empty(body) || st_empty(boundary)) {
		return pl_null();
	}

	// Figure out the lengths.
	if (!(length = st_length_get(&body))) {
		log_pedantic("Cannot parse children from zero-length MIME body..");
		return pl_null();
	}
	else if (!(boundlen = st_length_get(boundary))) {
		log_pedantic("Cannot parse children from MIME body with zero-length boundary.");
		return pl_null();;
	}

	// Setup.
	stream = st_char_get(&body);
	bounddata = st_char_get(boundary);

	// Find the start of the first part.
	while (increment + boundlen <= length && result < child) {

		if (mm_cmp_cs_eq(stream, bounddata, boundlen) == 0 && (increment + boundlen == length || *(stream + boundlen) < '!' || *(stream + boundlen) > '~')) {
			stream += boundlen;
			increment += boundlen;

			// Two dashes indicate the end of this mime sections.
			if (increment < length && mm_cmp_cs_eq(stream, "--", 2) == 0) {
				increment = length + 1;
			}
			else {
				result++;
			}

		}
		else {
			stream++;
			increment++;
		}

	}

	// The requested child wasn't found.
	if (increment + boundlen >= length) {
		return pl_null();
	}

	// This will skip a line break after the boundary marker.
	if (length - increment > 0 && *stream == '\r') {
		stream++;
		increment++;
	}

	if (length - increment > 0 && *stream == '\n') {
		stream++;
		increment++;
	}

	// Store the start position.
	start = stream;

	// Find the end.
	while (increment < length) {

		if (increment + boundlen < length && mm_cmp_cs_eq(stream, bounddata, boundlen) == 0) {
			increment = length;
		}
		else {
			stream++;
			increment++;
		}
	}

	// Make sure we advanced.
	if (stream == start) {
		return pl_null();
	}

	return pl_init(start, stream - start);
}
Пример #17
0
/**
 * @brief	Return a zero-length placer pointing to NULL data.
 * @return	a zero-length placer pointing to NULL data.
 */
placer_t pl_null(void) {

	return (placer_t){ .opts = PLACER_T | JOINTED | STACK | FOREIGNDATA, .data = NULL, .length = 0 };
}

/**
 * @brief	Return a placer wrapping a data buffer of given size.
 * @param	data	a pointer to the data to be wrapped.
 * @param	len		the length, in bytes, of the data.
 * @return	a placer pointing to the specified data.
 */
placer_t pl_init(void *data, size_t len) {

	return (placer_t){ .opts = PLACER_T | JOINTED | STACK | FOREIGNDATA, .data = data, .length = len };
}

placer_t pl_clone(placer_t place) {
	return (pl_init(place.data, place.length));
}

placer_t pl_set(placer_t place, placer_t set) {

	return (placer_t){ .opts = place.opts, .data = set.data, .length = set.length };
}

/**
 * @brief	Get a pointer to the data referenced by a placer.
 * @param	place	the input placer.
 * @return	NULL on failure or a pointer to the block of data associated with the specified placer on success.
 */
void * pl_data_get(placer_t place) {

	return st_data_get((stringer_t *)&place);
}

/**
 * @brief	Get a character pointer to the data referenced by a placer.
 * @param	place	the input placer.
 * @return	NULL on failure or a a character pointer to the block of data associated with the specified placer on success.
 */
chr_t * pl_char_get(placer_t place) {

	return st_char_get((stringer_t *)&place);
}

/**
 * @brief	Get the length, in bytes, of a placer as an integer.
 * @param	place	the input placer.
 * @return	the size, in bytes, of the specified placer.
 */
int_t pl_length_int(placer_t place) {

	return st_length_int((stringer_t *)&place);
}

/**
 * @brief	Get the length, in bytes, of a placer.
 * @param	place	the input placer.
 * @return	the size, in bytes, of the specified placer.
 */
size_t pl_length_get(placer_t place) {

	return st_length_get((stringer_t *)&place);
}

/**
 * @brief	Determine whether or not the specified placer is empty.
 * @param	place	the input placer.
 * @return	true if the placer is empty or zero-length, or false otherwise.
 */
bool_t pl_empty(placer_t place) {

	return st_empty((stringer_t *)&place);
}

/**
 * @brief	Determine if a placer begins with a specified character.
 * @param	place	the input placer.
 * @param	c		the character to be compared with the first byte of the placer's data.
 * @return	true if the placer begins with the given character or false otherwise.
 */
bool_t pl_starts_with_char(placer_t place, chr_t c) {

	if (pl_empty(place)) {
		return false;
	}

	if (*(pl_char_get(place)) == c) {
		return true;
	}

	return false;
}

/**
 * @brief	Advance the placer one character forward beyond an expected character.
 * @param	place	the input placer.
 * @param	more	if true, the placer must contain more data, and vice versa.
 * @return	true if more was true and the placer contains more data, or if more was false and the placer ended; false otherwise.
 */
bool_t pl_inc(placer_t *place, bool_t more) {

	if (pl_empty(*place)) {
		return false;
	}

	place->length--;
	place->data = (chr_t *)place->data + 1;

	return (more == (place->length > 0));
}
Пример #18
0
int main(int argc, char **argv)
{
	if (argc == 1 || (argc == 2 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-help") || !strcmp(argv[1], "-h")))) {
		PrintHelp();
		return 0;
	}

	emu_core_preinit();
	ChangeWorkingDirectory("c");
	char file[MAXPATHLEN] = "";
	char path[MAXPATHLEN];
	const char *cdfile = NULL;
	int loadst = 0;
	int i;
	int getst = -1;
	int discNumber = 0;

	g_menuscreen_w = 800;
	g_menuscreen_h = 480;

	strcpy(Config.Gpu, "builtin_gpu");
	strcpy(Config.Spu, "builtin_spu");
	strcpy(Config.BiosDir, "/home/user/MyDocs");
	strcpy(Config.PluginsDir, "/opt/maemo/usr/games/plugins");
	snprintf(Config.PatchesDir, sizeof(Config.PatchesDir), "/opt/maemo/usr/games" PATCHES_DIR);
	Config.PsxAuto = 1;
	pl_rearmed_cbs.frameskip = -1;
	strcpy(Config.Bios, "HLE");
    iUseReverb = 0;
    iUseInterpolation = 0;

	in_type1 = PSE_PAD_TYPE_STANDARD;
	in_type2 = PSE_PAD_TYPE_STANDARD;

	accelOptions.sens     = 150;
	accelOptions.y_def	  = 500;
	accelOptions.maxValue = 500.0;

	// read command line options
	for (i = 1; i < argc; i++) {
		     if (!strcmp(argv[i], "-psxout")) Config.PsxOut = 1;
		else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
		else if (!strcmp(argv[i], "-cdfile")) {
			char isofilename[MAXPATHLEN];
			if (i+1 >= argc) break;
			strncpy(isofilename, argv[++i], MAXPATHLEN);
			if (isofilename[0] != '/') {
				getcwd(path, MAXPATHLEN);
				if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
					strcat(path, "/");
					strcat(path, isofilename);
					strcpy(isofilename, path);
				} else
					isofilename[0] = 0;
			}
			cdfile = isofilename;
		}
		else if (!strcmp(argv[i],"-frameskip")) {
			int tv_reg = atol(argv[++i]);
			if (tv_reg < -1)
				pl_rearmed_cbs.frameskip = -1;
			else
				pl_rearmed_cbs.frameskip = tv_reg;
		}
		else if (!strcmp(argv[i],"-region")) {
			int psx_reg = atol(argv[++i]);
			if (psx_reg == 0 || psx_reg == 1){
				Config.PsxAuto = 0;
				Config.PsxType = psx_reg;
			}
		}

		else if (!strcmp(argv[i],"-get_sstatename")) getst = atol(argv[++i]);

		else if (!strcmp(argv[i], "-fullscreen"))	        g_maemo_opts |= 2;
		else if (!strcmp(argv[i], "-accel"))				g_maemo_opts |= 4;
		else if (!strcmp(argv[i], "-nosound"))		        strcpy(Config.Spu, "spunull.so");
		else if (!strcmp(argv[i], "-bdir"))			sprintf(Config.BiosDir, "%s", argv[++i]);
		else if (!strcmp(argv[i], "-pdir"))			        sprintf(Config.PluginsDir, "%s", argv[++i]);
		else if (!strcmp(argv[i], "-bios"))			sprintf(Config.Bios, "%s", argv[++i]);
		else if (!strcmp(argv[i], "-gles"))			        { strcpy(Config.Gpu, "gpu_gles.so"); g_maemo_opts |= 8 ;}
		else if (!strcmp(argv[i], "-oldgpu"))		        strcpy(Config.Gpu, "gpu_peops.so");
		else if (!strcmp(argv[i], "-unai"))		            strcpy(Config.Gpu, "gpu_unai.so");
		else if (!strcmp(argv[i], "-cdda"))		Config.Cdda = 1;
		else if (!strcmp(argv[i], "-xa"))		Config.Xa = 1;
		else if (!strcmp(argv[i], "-rcnt"))		Config.RCntFix = 1 ;
		else if (!strcmp(argv[i], "-sio"))		Config.Sio = 1;
		else if (!strcmp(argv[i], "-spuirq"))	Config.SpuIrq = 1;
		else if (!strcmp(argv[i], "-vsync"))	Config.VSyncWA = 1;
		else if (!strcmp(argv[i], "-fps")) 		            g_opts |=OPT_SHOWFPS;
		else if (!strcmp(argv[i], "-cpu")) 		            g_opts |=OPT_SHOWCPU;
		else if (!strcmp(argv[i], "-spu")) 		            g_opts |=OPT_SHOWSPU;
		else if (!strcmp(argv[i], "-nofl")) 		        g_opts |=OPT_NO_FRAMELIM;
		else if (!strcmp(argv[i], "-mcd1")) 	            sprintf(Config.Mcd1, "%s", argv[++i]);
		else if (!strcmp(argv[i], "-mcd2")) 	            sprintf(Config.Mcd2, "%s", argv[++i]);

		else if (!strcmp(argv[i], "-cpuclock")) 	        cycle_multiplier = 10000 / atol(argv[++i]);
		else if (!strcmp(argv[i], "-guncon")) 	            in_type1 = PSE_PAD_TYPE_GUNCON;
		else if (!strcmp(argv[i], "-gunnotrigger")) 		g_opts |= OPT_TSGUN_NOTRIGGER;
		else if (!strcmp(argv[i], "-analog")) 	            in_type1 = PSE_PAD_TYPE_ANALOGPAD;
		else if (!strcmp(argv[i], "-vibration")) 	        { in_type1 = PSE_PAD_TYPE_ANALOGPAD; in_enable_vibration = 1; }
		else if (!strcmp(argv[i], "-sens")) 				accelOptions.sens = atol(argv[++i]);
		else if (!strcmp(argv[i], "-ydef")) 				accelOptions.y_def = atol(argv[++i]);
		else if (!strcmp(argv[i], "-max")) 				    accelOptions.maxValue = atol(argv[++i]);
		else if (!strcmp(argv[i], "-displayon")) 		    bKeepDisplayOn = TRUE;
		else if (!strcmp(argv[i], "-keys")) 				sprintf(keys_config_file, "%s", argv[++i]);
		else if (!strcmp(argv[i], "-autosave")) 		    bAutosaveOnExit = TRUE;
		else if (!strcmp(argv[i], "-disc")) 		        discNumber = atol(argv[++i]);
		else if (!strcmp(argv[i], "-corners")){
			int j = 0;
			i++;
			char num[2];
			for (j=0; j<strlen(argv[i]); j++){
				strncpy(num, argv[i] + j, 1);
				cornerActions[j] = atoi(num);
			}
	}

		else if (!strcmp(argv[i], "-spu_reverb"))           { if (atol(argv[++i]) > 0) iUseReverb = 2; }
		else if (!strcmp(argv[i], "-spu_interpolation")) 	iUseInterpolation = atol(argv[++i]);

		else if (!strcmp(argv[i],"-interlace")) {
			int interlace = atol(argv[++i]);
			if (interlace >= 0 && interlace <= 2)
				pl_rearmed_cbs.gpu_neon.allow_interlace = interlace;
		}
		else if (!strcmp(argv[i], "-enhance")) 			pl_rearmed_cbs.gpu_neon.enhancement_enable = 1;
		else if (!strcmp(argv[i], "-enhancehack")) 		pl_rearmed_cbs.gpu_neon.enhancement_no_main = 1;

		else if (!strcmp(argv[i], "-gles_dithering")) 	pl_rearmed_cbs.gpu_peopsgl.bDrawDither = atol(argv[++i]);
		else if (!strcmp(argv[i], "-gles_mask")) 	    pl_rearmed_cbs.gpu_peopsgl.iUseMask = atol(argv[++i]);
		else if (!strcmp(argv[i], "-gles_filtering")) 	pl_rearmed_cbs.gpu_peopsgl.iFilterType = atol(argv[++i]);
		else if (!strcmp(argv[i], "-gles_fbtex")) 	    pl_rearmed_cbs.gpu_peopsgl.iFrameTexType = atol(argv[++i]);
		else if (!strcmp(argv[i], "-gles_vram")) 	    pl_rearmed_cbs.gpu_peopsgl.iVRamSize = atol(argv[++i]);
		else if (!strcmp(argv[i], "-gles_fastmdec")) 	pl_rearmed_cbs.gpu_peopsgl.bUseFastMdec = atol(argv[++i]);
        else if (!strcmp(argv[i], "-gles_advblend")) 	pl_rearmed_cbs.gpu_peopsgl.bAdvancedBlend = atol(argv[++i]);
        else if (!strcmp(argv[i], "-gles_opaque")) 	    pl_rearmed_cbs.gpu_peopsgl.bOpaquePass = atol(argv[++i]);

		else {
			fprintf(stderr, "Unknown option: %s\n", argv[i]);
			return 1;
		}
	}
	
	pl_init();
	if (emu_core_init() == -1)
		return 1;
	
	if (cdfile) {
		set_cd_image(cdfile);
		strcpy(file_name, strrchr(cdfile,'/'));
	}

	if (LoadPlugins() == -1) {
		SysMessage("Failed loading plugins!");
		return 1;
	}

	if (discNumber > 0)
		cdrIsoMultidiskSelect = discNumber - 1;

	if (OpenPlugins() == -1) {
		return 1;
	}
	plugin_call_rearmed_cbs();

	CheckCdrom();

	if (getst >= 0){
		char fname[MAXPATHLEN];

		get_state_filename(fname, sizeof(fname), getst);
		printf("SAVESTATE: %s\n", fname);
		if (cdrIsoMultidiskCount > 1){
			int i = 0;
			for (i=1; i<cdrIsoMultidiskCount; i++){
				cdrIsoMultidiskSelect = i;
				CdromId[0] = '\0';
				CdromLabel[0] = '\0';

				CDR_close();
				if (CDR_open() == 0){
					CheckCdrom();
					get_state_filename(fname, sizeof(fname), getst);
					printf("SAVESTATE: %s\n", fname);
				}
			}
		}
		return 0;
	}

	SysReset();

	if (file[0] != '\0') {
		if (Load(file) != -1)
			ready_to_go = 1;
	} else {
		if (cdfile) {
			if (LoadCdrom() == -1) {
				ClosePlugins();
				printf(_("Could not load CD-ROM!\n"));
				return -1;
			}
			emu_on_new_cd(0);
			ready_to_go = 1;
		}
	}

	if (!ready_to_go) {
		printf ("something goes wrong, maybe you forgot -cdfile ? \n");
		return 1;
	}

	if (cdrIsoMultidiskCount > 1)
		printf ("Loaded a multidisc image: %i discs.\n", cdrIsoMultidiskCount);

	// If a state has been specified, then load that
	if (loadst) {
		int ret = emu_load_state(loadst - 1);
		printf("%s state %d\n", ret ? "Failed to load" : "Loaded", loadst);
		state_slot = loadst - 1;
	}

	if (maemo_init(&argc, &argv))
		return 1;

	if (GPU_open != NULL) {
		int ret = GPU_open(&gpuDisp, "PCSX", NULL);
		if (ret){
			fprintf(stderr, "Warning: GPU_open returned %d\n", ret);
			gpuDisp=ret;
		}
	}

	if (Config.HLE)
		printf("Note: running without BIOS, expect compatibility problems\n");

	dfinput_activate();
	pl_timing_prepare(Config.PsxType);

	while (1)
	{
		stop = 0;
		emu_action = SACTION_NONE;

		psxCpu->Execute();
		if (emu_action != SACTION_NONE)
			do_emu_action();
	}

	maemo_finish();
	return 0;
}
Пример #19
0
int main(int argc, char *argv[])
{
	char file[MAXPATHLEN] = "";
	char path[MAXPATHLEN];
	const char *cdfile = NULL;
	const char *loadst_f = NULL;
	int psxout = 0;
	int loadst = 0;
	int i;

	emu_core_preinit();

	// read command line options
	for (i = 1; i < argc; i++) {
		     if (!strcmp(argv[i], "-psxout")) psxout = 1;
		else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
		else if (!strcmp(argv[i], "-cfg")) {
			if (i+1 >= argc) break;
			strncpy(cfgfile_basename, argv[++i], MAXPATHLEN-100);	/* TODO buffer overruns */
			SysPrintf("Using config file %s.\n", cfgfile_basename);
		}
		else if (!strcmp(argv[i], "-cdfile")) {
			char isofilename[MAXPATHLEN];

			if (i+1 >= argc) break;
			strncpy(isofilename, argv[++i], MAXPATHLEN);
			if (isofilename[0] != '/') {
				getcwd(path, MAXPATHLEN);
				if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
					strcat(path, "/");
					strcat(path, isofilename);
					strcpy(isofilename, path);
				} else
					isofilename[0] = 0;
			}

			cdfile = isofilename;
		}
		else if (!strcmp(argv[i], "-loadf")) {
			if (i+1 >= argc) break;
			loadst_f = argv[++i];
		}
		else if (!strcmp(argv[i], "-h") ||
			 !strcmp(argv[i], "-help") ||
			 !strcmp(argv[i], "--help")) {
			 printf("PCSX-ReARMed " REV "\n");
			 printf("%s\n", _(
							" pcsx [options] [file]\n"
							"\toptions:\n"
							"\t-cdfile FILE\tRuns a CD image file\n"
							"\t-cfg FILE\tLoads desired configuration file (default: ~/.pcsx/pcsx.cfg)\n"
							"\t-psxout\t\tEnable PSX output\n"
							"\t-load STATENUM\tLoads savestate STATENUM (1-5)\n"
							"\t-h -help\tDisplay this message\n"
							"\tfile\t\tLoads a PSX EXE file\n"));
			 return 0;
		} else {
			strncpy(file, argv[i], MAXPATHLEN);
			if (file[0] != '/') {
				getcwd(path, MAXPATHLEN);
				if (strlen(path) + strlen(file) + 1 < MAXPATHLEN) {
					strcat(path, "/");
					strcat(path, file);
					strcpy(file, path);
				} else
					file[0] = 0;
			}
		}
	}

	if (cdfile)
		set_cd_image(cdfile);

	// frontend stuff
	// init input but leave probing to platform code,
	// they add input drivers and may need to modify them after probe
	in_init();
	pl_init();
	plat_init();
	menu_init(); // loads config

	if (emu_core_init() != 0)
		return 1;

	if (psxout)
		Config.PsxOut = 1;

	if (LoadPlugins() == -1) {
		// FIXME: this recovery doesn't work, just delete bad config and bail out
		// SysMessage("could not load plugins, retrying with defaults\n");
		set_default_paths();
		snprintf(path, sizeof(path), "." PCSX_DOT_DIR "%s", cfgfile_basename);
		remove(path);
		SysMessage("Failed loading plugins!");
		return 1;
	}
	pcnt_hook_plugins();

	if (OpenPlugins() == -1) {
		return 1;
	}
	plugin_call_rearmed_cbs();

	CheckCdrom();
	SysReset();

	if (file[0] != '\0') {
		if (Load(file) != -1)
			ready_to_go = 1;
	} else {
		if (cdfile) {
			if (LoadCdrom() == -1) {
				ClosePlugins();
				SysPrintf(_("Could not load CD-ROM!\n"));
				return -1;
			}
			emu_on_new_cd(!loadst);
			ready_to_go = 1;
		}
	}

	if (loadst_f) {
		int ret = LoadState(loadst_f);
		SysPrintf("%s state file: %s\n",
			ret ? "failed to load" : "loaded", loadst_f);
		ready_to_go |= ret == 0;
	}

	if (ready_to_go) {
		menu_prepare_emu();

		// If a state has been specified, then load that
		if (loadst) {
			int ret = emu_load_state(loadst - 1);
			SysPrintf("%s state %d\n",
				ret ? "failed to load" : "loaded", loadst);
		}
	}
	else
		menu_loop();

	pl_start_watchdog();

	while (!g_emu_want_quit)
	{
		stop = 0;
		emu_action = SACTION_NONE;

		psxCpu->Execute();
		if (emu_action != SACTION_NONE)
			do_emu_action();
	}

	printf("Exit..\n");
	ClosePlugins();
	SysClose();
	menu_finish();
	plat_finish();

	return 0;
}
Пример #20
0
/**
 * @brief	Decrypt a block of data using an ECIES private key.
 * @param	key			the ECIES private key in the specified format.
 * @param	key_type	the encoding type of the ECIES private key (ECIES_PRIVATE_BINARY or ECIES_PRIVATE_HEX).
 * @param	cryptex		a pointer to the head of the cryptex object with the encrypted data.
 * @param	length		a pointer to a size_t variable which will receive the final length of the unencrypted data.
 * @return	NULL on failure, or a pointer to a memory address containing the decrypted data on success..
 */
uchr_t * deprecated_ecies_decrypt(stringer_t *key, ECIES_KEY_TYPE key_type, cryptex_t *cryptex, size_t *length) {

	HMAC_CTX hmac;
	size_t key_length;
	int output_length;
	EVP_CIPHER_CTX cipher;
	EC_KEY *user, *ephemeral;
	uchr_t *kbuf;
	size_t hexkey_length;
	unsigned int mac_length = EVP_MAX_MD_SIZE;
	unsigned char envelope_key[SHA512_DIGEST_LENGTH], iv[EVP_MAX_IV_LENGTH], md[EVP_MAX_MD_SIZE], *block, *output;

	// Simple sanity check.
	if (!key || !cryptex || !length) {
		log_info("Invalid parameters passed in.");
		return NULL;
	}
	else if ((key_type != ECIES_PRIVATE_HEX) && (key_type != ECIES_PRIVATE_BINARY)) {
		log_info("Invalid ecies private key type specified!");
		return NULL;
	}
	else if (st_empty_out(key,&kbuf,&hexkey_length)) {
		log_info("Could not read key data.");
		return NULL;
	}
	// Make sure we are generating enough key material for the symmetric ciphers.
	else if ((key_length = EVP_CIPHER_key_length_d(EVP_get_cipherbyname_d(OBJ_nid2sn_d(ECIES_CIPHER)))) * 2 > SHA512_DIGEST_LENGTH) {
		log_info("The key derivation method will not produce enough envelope key material for the chosen ciphers. {envelope = %i / required = %zu}", SHA512_DIGEST_LENGTH / 8, (key_length * 2) / 8);
		return NULL;
	}
	// Convert the user's public key from hex into a full EC_KEY structure.
	else if (!(user = deprecated_ecies_key_private(key_type, pl_init(kbuf, hexkey_length)))) {
		log_info("Invalid private key provided.");
		return NULL;
	}
	// Create the ephemeral key used specifically for this block of data.
	else if (!(ephemeral = deprecated_ecies_key_public(ECIES_PUBLIC_BINARY, pl_init(deprecated_cryptex_envelope_data(cryptex), deprecated_cryptex_envelope_length(cryptex))))) {
		log_info("An error occurred while trying to recreate the ephemeral key.");
		EC_KEY_free_d(user);
		return NULL;
	}
	// Use the intersection of the provided keys to generate the envelope data used by the ciphers below. The ecies_key_derivation() function uses
	// SHA 512 to ensure we have a sufficient amount of envelope key material and that the material created is sufficiently secure.
	else if (ECDH_compute_key_d(envelope_key, SHA512_DIGEST_LENGTH, EC_KEY_get0_public_key_d(ephemeral), user, deprecated_ecies_envelope_derivation) != SHA512_DIGEST_LENGTH) {
		log_info("An error occurred while trying to compute the envelope key. {%s}", ssl_error_string(MEMORYBUF(256), 256));
		EC_KEY_free_d(ephemeral);
		EC_KEY_free_d(user);
		return NULL;
	}

	// The envelope key material has been extracted, so we no longer need the user and ephemeral keys.
	EC_KEY_free_d(ephemeral);
	EC_KEY_free_d(user);

	// Use the authenticated hash of the ciphered data to ensure it was not modified after being encrypted.
	HMAC_CTX_init_d(&hmac);

	// At the moment we are generating the hash using encrypted data. At some point we may want to validate the original text instead.
	if (HMAC_Init_ex_d(&hmac, envelope_key + key_length, key_length, EVP_get_digestbyname_d(OBJ_nid2sn_d(ECIES_HMAC)), NULL) != 1 || HMAC_Update_d(&hmac, deprecated_cryptex_body_data(cryptex), deprecated_cryptex_body_length(cryptex)) != 1 || HMAC_Final_d(&hmac, md, &mac_length) != 1) {
		log_info("Unable to generate the authentication code needed for validation. {%s}", ssl_error_string(MEMORYBUF(256), 256));
		HMAC_CTX_cleanup_d(&hmac);
		return NULL;
	}

	HMAC_CTX_cleanup_d(&hmac);

	// We can use the generated hash to ensure the encrypted data was not altered after being encrypted.
	if (mac_length != deprecated_cryptex_hmac_length(cryptex) || memcmp(md, deprecated_cryptex_hmac_data(cryptex), mac_length)) {
		log_info("The authentication code was invalid! The ciphered data has been corrupted!");
		return NULL;
	}

	// Create a buffer to hold the result.
	output_length = deprecated_cryptex_body_length(cryptex);

	if (!(block = output = mm_alloc(output_length + 1))) {
		log_info("An error occurred while trying to allocate memory for the decrypted data.");
		return NULL;
	}

	// For now we use an empty initialization vector. We also clear out the result buffer just to be on the safe side.
	memset(iv, 0, EVP_MAX_IV_LENGTH);
	memset(output, 0, output_length + 1);

	EVP_CIPHER_CTX_init_d(&cipher);

	// Decrypt the data using the chosen symmetric cipher.
	if (EVP_DecryptInit_ex_d(&cipher, EVP_get_cipherbyname_d(OBJ_nid2sn_d(ECIES_CIPHER)), NULL, envelope_key, iv) != 1 || EVP_CIPHER_CTX_set_padding_d(&cipher, 0) != 1 || EVP_DecryptUpdate_d(&cipher, block, &output_length, deprecated_cryptex_body_data(cryptex),
			deprecated_cryptex_body_length(cryptex)) != 1) {
		log_info("Unable to decrypt the data using the chosen symmetric cipher. {%s}", ssl_error_string(MEMORYBUF(256), 256));
		EVP_CIPHER_CTX_cleanup_d(&cipher);
		free(output);
		return NULL;
	}

	block += output_length;

	if ((output_length = deprecated_cryptex_body_length(cryptex) - output_length) != 0) {
		log_info("The symmetric cipher failed to properly decrypt the correct amount of data!");
		EVP_CIPHER_CTX_cleanup_d(&cipher);
		free(output);
		return NULL;
	}

	if (EVP_DecryptFinal_ex_d(&cipher, block, &output_length) != 1) {
		log_info("Unable to decrypt the data using the chosen symmetric cipher. {%s}", ssl_error_string(MEMORYBUF(256), 256));
		EVP_CIPHER_CTX_cleanup_d(&cipher);
		free(output);
		return NULL;
	}

	EVP_CIPHER_CTX_cleanup_d(&cipher);

	*length = deprecated_cryptex_original_length(cryptex);

	return output;
}
Пример #21
0
/**
 * @brief	Encrypt a block of data using an ECIES public key.
 * @param	key			the ECIES public key in the specified format.
 * @param	key_type	the encoding type of the ECIES public key (ECIES_PUBLIC_BINARY or ECIES_PUBLIC_HEX).
 * @param	data		a pointer to the block of data to be encrypted.
 * @param	length		the length, in bytes, of the data to be encrypted.
 * @return	NULL on failure, or a pointer to the header of the cryptex object containing the encrypted data on success..
 */
cryptex_t * deprecated_ecies_encrypt(stringer_t *key, ECIES_KEY_TYPE key_type, unsigned char *data, size_t length) {

	void *body;
	HMAC_CTX hmac;
	int body_length;
	cryptex_t *cryptex;
	EVP_CIPHER_CTX cipher;
	unsigned int mac_length;
	EC_KEY *user, *ephemeral;
	size_t envelope_length = 0, block_length = 0, key_length = 0, hexkey_length = 0;
	uchr_t *kbuf;
	unsigned char envelope_key[SHA512_DIGEST_LENGTH], iv[EVP_MAX_IV_LENGTH], block[EVP_MAX_BLOCK_LENGTH];

	// Simple sanity check.
	if (!key || !data || !length) {
		log_info("Invalid parameters passed in.");
		return NULL;
	}
	else if ((key_type != ECIES_PUBLIC_HEX) && (key_type != ECIES_PUBLIC_BINARY)) {
		log_info("Invalid ecies private key type specified!");
		return NULL;
	}
	else if (st_empty_out(key,&kbuf,&hexkey_length)) {
		log_info("Could not read key data.");
		return NULL;
	}

	// Make sure we are generating enough key material for the symmetric ciphers.
	if ((key_length = EVP_CIPHER_key_length_d(EVP_get_cipherbyname_d(OBJ_nid2sn_d(ECIES_CIPHER)))) * 2 > SHA512_DIGEST_LENGTH) {
		log_info("The key derivation method will not produce enough envelope key material for the chosen ciphers. {envelope = %i / required = %zu}", SHA512_DIGEST_LENGTH / 8, (key_length * 2) / 8);
		return NULL;
	}
	// Convert the user's public key from hex into a full EC_KEY structure.
	if (!(user = deprecated_ecies_key_public(key_type, pl_init(kbuf, hexkey_length)))) {
		log_info("Invalid public key provided.");
		return NULL;
	}
	// Create the ephemeral key used specifically for this block of data.
	else if (!(ephemeral = deprecated_ecies_key_create())) {
		log_info("An error occurred while trying to generate the ephemeral key.");
		EC_KEY_free_d(user);
		return NULL;
	}
	// Use the intersection of the provided keys to generate the envelope data used by the ciphers below. The ecies_key_derivation() function uses
	// SHA 512 to ensure we have a sufficient amount of envelope key material and that the material created is sufficiently secure.
	else if (ECDH_compute_key_d(envelope_key, SHA512_DIGEST_LENGTH, EC_KEY_get0_public_key_d(user), ephemeral, deprecated_ecies_envelope_derivation) != SHA512_DIGEST_LENGTH) {
		log_info("An error occurred while trying to compute the envelope key. {%s}", ssl_error_string(MEMORYBUF(256), 256));
		EC_KEY_free_d(ephemeral);
		EC_KEY_free_d(user);
		return NULL;
	}
	// Determine the envelope and block lengths so we can allocate a buffer for the result.
	else if ((block_length = EVP_CIPHER_block_size_d(EVP_get_cipherbyname_d(OBJ_nid2sn_d(ECIES_CIPHER)))) == 0 || block_length > EVP_MAX_BLOCK_LENGTH || (envelope_length = EC_POINT_point2oct_d(EC_KEY_get0_group_d(ephemeral), EC_KEY_get0_public_key_d(ephemeral),
			POINT_CONVERSION_COMPRESSED, NULL, 0, NULL)) == 0) {
		log_info("Invalid block or envelope length. {block = %zu / envelope = %zu}", block_length, envelope_length);
		EC_KEY_free_d(ephemeral);
		EC_KEY_free_d(user);
		return NULL;
	}
	// We use a conditional to pad the length if the input buffer is not evenly divisible by the block size.
	else if (!(cryptex = deprecated_cryptex_alloc(envelope_length, EVP_MD_size_d(EVP_get_digestbyname_d(OBJ_nid2sn_d(ECIES_HMAC))), length, length + (length % block_length ? (block_length - (length % block_length)) : 0)))) {
		log_info("Unable to allocate a secure_t buffer to hold the encrypted result.");
		EC_KEY_free_d(ephemeral);
		EC_KEY_free_d(user);
		return NULL;
	}
	// Store the public key portion of the ephemeral key.
	else if (EC_POINT_point2oct_d(EC_KEY_get0_group_d(ephemeral), EC_KEY_get0_public_key_d(ephemeral), POINT_CONVERSION_COMPRESSED, deprecated_cryptex_envelope_data(cryptex), envelope_length, NULL) != envelope_length) {
		log_info("An error occurred while trying to record the public portion of the envelope key. {%s}", ssl_error_string(MEMORYBUF(256), 256));
		EC_KEY_free_d(ephemeral);
		EC_KEY_free_d(user);
		deprecated_cryptex_free(cryptex);
		return NULL;
	}
	// The envelope key has been stored so we no longer need to keep the keys around.
	EC_KEY_free_d(ephemeral);
	EC_KEY_free_d(user);

	// For now we use an empty initialization vector.
	// LOW: Develop a more secure method for selecting and storing the initialization vector.
	memset(iv, 0, EVP_MAX_IV_LENGTH);

	// Setup the cipher context, the body length, and store a pointer to the body buffer location.
	EVP_CIPHER_CTX_init_d(&cipher);
	body = deprecated_cryptex_body_data(cryptex);
	body_length = deprecated_cryptex_body_length(cryptex);

	// Initialize the cipher with the envelope key.
	if (EVP_EncryptInit_ex_d(&cipher, EVP_get_cipherbyname_d(OBJ_nid2sn_d(ECIES_CIPHER)), NULL, envelope_key, iv) != 1 || EVP_CIPHER_CTX_set_padding_d(&cipher, 0) != 1 ||
			EVP_EncryptUpdate_d(&cipher, body, &body_length, data, length - (length % block_length)) != 1) {
		log_info("An error occurred while trying to secure the data using the chosen symmetric cipher. {%s}", ssl_error_string(MEMORYBUF(256), 256));
		EVP_CIPHER_CTX_cleanup_d(&cipher);
		deprecated_cryptex_free(cryptex);
		return NULL;
	}
	// Check whether all of the data was encrypted. If they don't match up, we either have a partial block remaining, or an error occurred.
	else if (body_length != length) {

		// Make sure all that remains is a partial block, and their wasn't an error.
		if (length - body_length >= block_length) {
			log_info("Unable to secure the data using the chosen symmetric cipher. {%s}", ssl_error_string(MEMORYBUF(256), 256));
			EVP_CIPHER_CTX_cleanup_d(&cipher);
			deprecated_cryptex_free(cryptex);
			return NULL;
		}

		// Copy the remaining data into our partial block buffer. The memset() call ensures any extra bytes will be zero'ed out.
		memset(block, 0, EVP_MAX_BLOCK_LENGTH);
		memcpy(block, data + body_length, length - body_length);
		// Advance the body pointer to the location of the remaining space, and calculate just how much room is still available.
		body += body_length;

		if ((body_length = deprecated_cryptex_body_length(cryptex) - body_length) < 0) {
			log_info("The symmetric cipher overflowed!");
			EVP_CIPHER_CTX_cleanup_d(&cipher);
			deprecated_cryptex_free(cryptex);
			return NULL;
		}
		// Pass the final partially filled data block into the cipher as a complete block. The padding will be removed during the decryption process.
		else if (EVP_EncryptUpdate_d(&cipher, body, &body_length, block, block_length) != 1) {
			log_info("Unable to secure the data using the chosen symmetric cipher. {%s}", ssl_error_string(MEMORYBUF(256), 256));
			EVP_CIPHER_CTX_cleanup_d(&cipher);
			deprecated_cryptex_free(cryptex);
			return NULL;
		}

	}
	// Advance the pointer, then use pointer arithmetic to calculate how much of the body buffer has been used. The complex logic is needed so that we get
	// the correct status regardless of whether there was a partial data block.
	body += body_length;

	if ((body_length = deprecated_cryptex_body_length(cryptex) - (body - deprecated_cryptex_body_data(cryptex))) < 0) {
		log_info("The symmetric cipher overflowed!");
		EVP_CIPHER_CTX_cleanup_d(&cipher);
		deprecated_cryptex_free(cryptex);
		return NULL;
	} else if (EVP_EncryptFinal_ex_d(&cipher, body, &body_length) != 1) {
		log_info("Unable to secure the data using the chosen symmetric cipher. {%s}", ssl_error_string(MEMORYBUF(256), 256));
		EVP_CIPHER_CTX_cleanup_d(&cipher);
		deprecated_cryptex_free(cryptex);
		return NULL;
	}

	EVP_CIPHER_CTX_cleanup_d(&cipher);

	// Generate an authenticated hash which can be used to validate the data during decryption.
	HMAC_CTX_init_d(&hmac);
	mac_length = deprecated_cryptex_hmac_length(cryptex);

	// At the moment we are generating the hash using encrypted data. At some point we may want to validate the original text instead.
	if (HMAC_Init_ex_d(&hmac, envelope_key + key_length, key_length, EVP_get_digestbyname_d(OBJ_nid2sn_d(ECIES_HMAC)), NULL) != 1 || HMAC_Update_d(&hmac, deprecated_cryptex_body_data(cryptex), deprecated_cryptex_body_length(cryptex)) != 1 || HMAC_Final_d(&hmac, deprecated_cryptex_hmac_data(
			cryptex), &mac_length) != 1) {
		log_info("Unable to generate a data authentication code. {%s}", ssl_error_string(MEMORYBUF(256), 256));
		HMAC_CTX_cleanup_d(&hmac);
		deprecated_cryptex_free(cryptex);
		return NULL;
	}

	HMAC_CTX_cleanup_d(&hmac);

	return cryptex;
}
Пример #22
0
int
main (int argc, char *argv[]) {
    int portable = 0;
#if STATICLINK
    int staticlink = 1;
#else
    int staticlink = 0;
#endif
#if PORTABLE
    portable = 1;
    if (!realpath (argv[0], dbinstalldir)) {
        strcpy (dbinstalldir, argv[0]);
    }
    char *e = strrchr (dbinstalldir, '/');
    if (e) {
        *e = 0;
    }
    else {
        fprintf (stderr, "couldn't determine install folder from path %s\n", argv[0]);
        exit (-1);
    }
#else
    if (!realpath (argv[0], dbinstalldir)) {
        strcpy (dbinstalldir, argv[0]);
    }
    char *e = strrchr (dbinstalldir, '/');
    if (e) {
        *e = 0;
        struct stat st;
        char checkpath[PATH_MAX];
        snprintf (checkpath, sizeof (checkpath), "%s/.ddb_portable", dbinstalldir);
        if (!stat (checkpath, &st)) {
            if (S_ISREG (st.st_mode)) {
                portable = 1;
            }
        }
    }
    if (!portable) {
        strcpy (dbinstalldir, PREFIX);
    }
#endif

#ifdef __GLIBC__
    signal (SIGSEGV, sigsegv_handler);
#endif
    setlocale (LC_ALL, "");
    setlocale (LC_NUMERIC, "C");
#ifdef ENABLE_NLS
//    fprintf (stderr, "enabling gettext support: package=" PACKAGE ", dir=" LOCALEDIR "...\n");
    if (portable) {
        char localedir[PATH_MAX];
        snprintf (localedir, sizeof (localedir), "%s/locale", dbinstalldir);
        bindtextdomain (PACKAGE, localedir);
    }
    else {
        bindtextdomain (PACKAGE, LOCALEDIR);
    }
	bind_textdomain_codeset (PACKAGE, "UTF-8");
	textdomain (PACKAGE);
#endif

    fprintf (stderr, "starting deadbeef " VERSION "%s%s\n", staticlink ? " [static]" : "", portable ? " [portable]" : "");
    srand (time (NULL));
#ifdef __linux__
    prctl (PR_SET_NAME, "deadbeef-main", 0, 0, 0, 0);
#endif

#if PORTABLE_FULL
    if (snprintf (confdir, sizeof (confdir), "%s/config", dbinstalldir) > sizeof (confdir)) {
        fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
        return -1;
    }

    strcpy (dbconfdir, confdir);
#else
    char *homedir = getenv ("HOME");
    if (!homedir) {
        fprintf (stderr, "unable to find home directory. stopping.\n");
        return -1;
    }

    char *xdg_conf_dir = getenv ("XDG_CONFIG_HOME");
    if (xdg_conf_dir) {
        if (snprintf (confdir, sizeof (confdir), "%s", xdg_conf_dir) > sizeof (confdir)) {
            fprintf (stderr, "fatal: XDG_CONFIG_HOME value is too long: %s\n", xdg_conf_dir);
            return -1;
        }
    }
    else {
        if (snprintf (confdir, sizeof (confdir), "%s/.config", homedir) > sizeof (confdir)) {
            fprintf (stderr, "fatal: HOME value is too long: %s\n", homedir);
            return -1;
        }
    }
    if (snprintf (dbconfdir, sizeof (dbconfdir), "%s/deadbeef", confdir) > sizeof (dbconfdir)) {
        fprintf (stderr, "fatal: out of memory while configuring\n");
        return -1;
    }
    mkdir (confdir, 0755);
#endif


    if (portable) {
        if (snprintf (dbdocdir, sizeof (dbdocdir), "%s/doc", dbinstalldir) > sizeof (dbdocdir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
#ifdef HAVE_COCOAUI
        char respath[PATH_MAX];
        cocoautil_get_resources_path (respath, sizeof (respath));
        if (snprintf (dbplugindir, sizeof (dbplugindir), "%s", respath) > sizeof (dbplugindir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
#else
        if (snprintf (dbplugindir, sizeof (dbplugindir), "%s/plugins", dbinstalldir) > sizeof (dbplugindir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
#endif
        if (snprintf (dbpixmapdir, sizeof (dbpixmapdir), "%s/pixmaps", dbinstalldir) > sizeof (dbpixmapdir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
        mkdir (dbplugindir, 0755);
    }
    else {
        if (snprintf (dbdocdir, sizeof (dbdocdir), "%s", DOCDIR) > sizeof (dbdocdir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
        if (snprintf (dbplugindir, sizeof (dbplugindir), "%s/deadbeef", LIBDIR) > sizeof (dbplugindir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
        if (snprintf (dbpixmapdir, sizeof (dbpixmapdir), "%s/share/deadbeef/pixmaps", PREFIX) > sizeof (dbpixmapdir)) {
            fprintf (stderr, "fatal: too long install path %s\n", dbinstalldir);
            return -1;
        }
    }

    for (int i = 1; i < argc; i++) {
        // help, version and nowplaying are executed with any filter
        if (!strcmp (argv[i], "--help") || !strcmp (argv[i], "-h")) {
            print_help ();
            return 0;
        }
        else if (!strcmp (argv[i], "--version")) {
            fprintf (stderr, "DeaDBeeF " VERSION " Copyright © 2009-2013 Alexey Yakovenko\n");
            return 0;
        }
        else if (!strcmp (argv[i], "--gui")) {
            if (i == argc-1) {
                break;
            }
            i++;
            strncpy (use_gui_plugin, argv[i], sizeof(use_gui_plugin) - 1);
            use_gui_plugin[sizeof(use_gui_plugin) - 1] = 0;
        }
    }

    trace ("installdir: %s\n", dbinstalldir);
    trace ("confdir: %s\n", confdir);
    trace ("docdir: %s\n", dbdocdir);
    trace ("plugindir: %s\n", dbplugindir);
    trace ("pixmapdir: %s\n", dbpixmapdir);

    mkdir (dbconfdir, 0755);

    int size = 0;
    char *cmdline = prepare_command_line (argc, argv, &size);

    // try to connect to remote player
    int s, len;
    struct sockaddr_un remote;

    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    memset (&remote, 0, sizeof (remote));
    remote.sun_family = AF_UNIX;
#if USE_ABSTRACT_SOCKET_NAME
    memcpy (remote.sun_path, server_id, sizeof (server_id));
    len = offsetof(struct sockaddr_un, sun_path) + sizeof (server_id)-1;
#else
    char *socketdirenv = getenv ("DDB_SOCKET_DIR");
    snprintf (remote.sun_path, sizeof (remote.sun_path), "%s/socket", socketdirenv ? socketdirenv : dbconfdir);
    len = offsetof(struct sockaddr_un, sun_path) + strlen (remote.sun_path);
#endif
    if (connect(s, (struct sockaddr *)&remote, len) == 0) {
        // pass args to remote and exit
        if (send(s, cmdline, size, 0) == -1) {
            perror ("send");
            exit (-1);
        }
        // end of message
        shutdown(s, SHUT_WR);

        int sz = -1;
        char *out = read_entire_message(s, &sz);
        if (sz == -1) {
            fprintf (stderr, "failed to pass args to remote!\n");
            exit (-1);
        }
        else {
            // check if that's nowplaying response
            const char np[] = "nowplaying ";
            const char err[] = "error ";
            if (!strncmp (out, np, sizeof (np)-1)) {
                const char *prn = &out[sizeof (np)-1];
                fwrite (prn, 1, strlen (prn), stdout);
            }
            else if (!strncmp (out, err, sizeof (err)-1)) {
                const char *prn = &out[sizeof (err)-1];
                fwrite (prn, 1, strlen (prn), stderr);
            }
            else if (sz > 0 && out[0]) {
                fprintf (stderr, "%s\n", out);
            }
        }
        if (out) {
            free (out);
        }
        close (s);
        exit (0);
    }
//    else {
//        perror ("INFO: failed to connect to existing session:");
//    }
    close(s);

    // become a server
    if (server_start () < 0) {
        exit (-1);
    }

    // hack: report nowplaying
    if (!strcmp (cmdline, "--nowplaying")) {
        char nothing[] = "nothing";
        fwrite (nothing, 1, sizeof (nothing)-1, stdout);
        return 0;
    }

    pl_init ();
    conf_init ();
    conf_load (); // required by some plugins at startup

    if (use_gui_plugin[0]) {
        conf_set_str ("gui_plugin", use_gui_plugin);
    }

    conf_set_str ("deadbeef_version", VERSION);

    volume_set_db (conf_get_float ("playback.volume", 0)); // volume need to be initialized before plugins start

    messagepump_init (); // required to push messages while handling commandline
    if (plug_load_all ()) { // required to add files to playlist from commandline
        exit (-1);
    }
    pl_load_all ();
    plt_set_curr_idx (conf_get_int ("playlist.current", 0));

    // execute server commands in local context
    int noloadpl = 0;
    if (argc > 1) {
        int res = server_exec_command_line (cmdline, size, NULL, 0);
        // some of the server commands ran on 1st instance should terminate it
        if (res == 2) {
            noloadpl = 1;
        }
        else if (res > 0) {
            exit (0);
        }
        else if (res < 0) {
            exit (-1);
        }
    }

    free (cmdline);

#if 0
    signal (SIGTERM, sigterm_handler);
    atexit (atexit_handler); // helps to save in simple cases
#endif

    streamer_init ();

    plug_connect_all ();
    messagepump_push (DB_EV_PLUGINSLOADED, 0, 0, 0);

    if (!noloadpl) {
        restore_resume_state ();
    }

    server_tid = thread_start (server_loop, NULL);

    mainloop_tid = thread_start (mainloop_thread, NULL);

    DB_plugin_t *gui = plug_get_gui ();
    if (gui) {
        gui->start ();
    }

    fprintf (stderr, "gui plugin has quit; waiting for mainloop thread to finish\n");
    thread_join (mainloop_tid);

    // terminate server and wait for completion
    if (server_tid) {
        server_terminate = 1;
        thread_join (server_tid);
        server_tid = 0;
    }

    // save config
    pl_save_all ();
    conf_save ();

    // delete legacy session file
    {
        char sessfile[1024]; // $HOME/.config/deadbeef/session
        if (snprintf (sessfile, sizeof (sessfile), "%s/deadbeef/session", confdir) < sizeof (sessfile)) {
            unlink (sessfile);
        }
    }

    // stop receiving messages from outside
    server_close ();

    // plugins might still hold references to playitems,
    // and query configuration in background
    // so unload everything 1st before final cleanup
    plug_disconnect_all ();
    plug_unload_all ();

    // at this point we can simply do exit(0), but let's clean up for debugging
    pl_free (); // may access conf_*
    conf_free ();

    fprintf (stderr, "messagepump_free\n");
    messagepump_free ();
    fprintf (stderr, "plug_cleanup\n");
    plug_cleanup ();

    fprintf (stderr, "hej-hej!\n");

    return 0;
}
Пример #23
0
void
kb_init(kb_t * kb, cmd_ln_t *config)
{
    kbcore_t *kbcore;
    mdef_t *mdef;
    dict_t *dict;
    dict2pid_t *d2p;
    int32 cisencnt;

    /* STRUCTURE: Initialize the kb structure to zero, just in case */
    memset(kb, 0, sizeof(*kb));
    kb->kbcore = kbcore_init(config);
    if (kb->kbcore == NULL)
        E_FATAL("Initialization of kb failed\n");

    kbcore = kb->kbcore;
    mdef = kbcore_mdef(kbcore);
    dict = kbcore_dict(kbcore);
    d2p = kbcore_dict2pid(kbcore);

    err_set_debug_level(cmd_ln_int32_r(config, "-debug"));

    /* STRUCTURE INITIALIZATION: Initialize the beam data structure */
    if (cmd_ln_exists_r(config, "-ptranskip")) {
        kb->beam = beam_init(cmd_ln_float64_r(config, "-beam"),
                             cmd_ln_float64_r(config, "-pbeam"),
                             cmd_ln_float64_r(config, "-wbeam"),
                             cmd_ln_float64_r(config, "-wend_beam"),
                             cmd_ln_int32_r(config, "-ptranskip"), mdef_n_ciphone(mdef),
                             kbcore->logmath
            );

        /* REPORT : Report the parameters in the beam data structure */
        if (REPORT_KB)
                beam_report(kb->beam);
    }


    /* STRUCTURE INITIALIZATION: Initialize the fast GMM computation data structure */
    if (cmd_ln_exists_r(config, "-ci_pbeam")) {
        kb->fastgmm = fast_gmm_init(cmd_ln_int32_r(config, "-ds"),
                                    cmd_ln_int32_r(config, "-cond_ds"),
                                    cmd_ln_int32_r(config, "-dist_ds"),
                                    cmd_ln_int32_r(config, "-gs4gs"),
                                    cmd_ln_int32_r(config, "-svq4svq"),
                                    cmd_ln_float64_r(config, "-subvqbeam"),
                                    cmd_ln_float64_r(config, "-ci_pbeam"),
                                    cmd_ln_float64_r(config, "-tighten_factor"),
                                    cmd_ln_int32_r(config, "-maxcdsenpf"),
                                    mdef->n_ci_sen,
                                    kbcore->logmath);

        /* REPORT : Report the parameters in the fast_gmm_t data struture */
        if (REPORT_KB)
            fast_gmm_report(kb->fastgmm);
    }

    /* STRUCTURE INITIALIZATION: Initialize the phoneme lookahead data structure */
    if (cmd_ln_exists_r(config, "-pl_beam")) {
        kb->pl = pl_init(cmd_ln_int32_r(config, "-pheurtype"),
                         cmd_ln_float64_r(config, "-pl_beam"), mdef_n_ciphone(mdef),
                         kbcore->logmath
            );

        /* REPORT : Report the parameters in the pl_t data struture */
        if (REPORT_KB)
            pl_report(kb->pl);
    }

    /* STRUCTURE INITIALIZATION: Initialize the acoustic score data structure */
    {
        int32 pl_window = 1;

        if (cmd_ln_exists_r(config, "-pl_window"))
            pl_window = cmd_ln_int32_r(config, "-pl_window");

        for (cisencnt = 0; cisencnt == mdef->cd2cisen[cisencnt]; cisencnt++) ;
        kb->ascr = ascr_init(kbcore_n_mgau(kbcore),
                             kb->kbcore->dict2pid->n_comstate,
                             mdef_n_sseq(mdef),
                             dict2pid_n_comsseq(d2p),
                             pl_window, cisencnt);

        if (REPORT_KB)
            ascr_report(kb->ascr);
    }

    /* Initialize the front end if -adcin is specified */
    if (cmd_ln_exists_r(config, "-adcin") && cmd_ln_boolean_r(config, "-adcin")) {
        if ((kb->fe = fe_init_auto_r(config)) == NULL) {
            E_FATAL("fe_init_auto_r() failed\n");
        }
    }
    /* STRUCTURE INITIALIZATION : The feature vector */
    if ((kb->feat =
         feat_array_alloc(kbcore_fcb(kbcore), S3_MAX_FRAMES)) == NULL)
        E_FATAL("feat_array_alloc() failed\n");

    /* STRUCTURE INITIALIZATION : The statistics for the search */
    kb->stat = stat_init();

    /* STRUCTURE INITIALIZATION : The adaptation routines of the search */
    kb->adapt_am = adapt_am_init();

    if (cmd_ln_str_r(config, "-mllr")) {
        kb_setmllr(cmd_ln_str_r(config, "-mllr"), cmd_ln_str_r(config, "-cb2mllr"), kb);
    }

    /* CHECK: make sure when (-cond_ds) is specified, a Gaussian map is also specified */
    if (cmd_ln_int32_r(config, "-cond_ds") > 0 && kb->kbcore->gs == NULL)
        E_FATAL
            ("Conditional Down Sampling require the use of Gaussian Selection map\n");

    /* MEMORY ALLOCATION : Word best score and exit */
    /* Open hypseg file if specified */
    kb->matchsegfp = kb->matchfp = NULL;
    kb->matchsegfp = file_open(cmd_ln_str_r(config, "-hypseg"));
    kb->matchfp = file_open(cmd_ln_str_r(config, "-hyp"));

    if (cmd_ln_exists_r(config, "-hmmdump"))
        kb->hmmdumpfp = cmd_ln_int32_r(config, "-hmmdump") ? stderr : NULL;

    /* STRUCTURE INITIALIZATION : The search data structure, done only
       after kb is initialized kb is acted as a clipboard. */
    if (cmd_ln_exists_r(config, "-op_mode")) {
        /* -op_mode, if set (i.e. not -1), takes precedence over -mode. */
        if (cmd_ln_int32_r(config, "-op_mode") != -1)
            kb->op_mode = cmd_ln_int32_r(config, "-op_mode");
        else
            kb->op_mode = srch_mode_str_to_index(cmd_ln_str_r(config, "-mode"));
        E_INFO("SEARCH MODE INDEX %d\n", kb->op_mode);
        if ((kb->srch = (srch_t *) srch_init(kb, kb->op_mode)) == NULL) {
            E_FATAL("Search initialization failed. Forced exit\n");
        }
        if (REPORT_KB) {
            srch_report(kb->srch);
        }
    }
}
Пример #24
0
void sl_init2(sl* list, int blocksize) {
	pl_init(list, blocksize);
}