Example #1
0
bool get_code_feature(
	const wchar_t * file_path,
	const unsigned int code_shift,
	const char * signatyre_data,
	const unsigned int signatyre_data_len)
{
	unsigned short Num = 0;
	CPeFile pe;
	auto st_size = get_file_data(file_path, nullptr);
	if (!st_size) {
		return false;
	}

	auto file_data = new char[st_size];
	if (!get_file_data(file_path, file_data)) {
		return false;
	}

	pe.Attach(file_path);
	auto herader = pe.GetSectionHeader(&Num);

	if (!herader) {
		return false;
	}

	auto he = herader[0];
	for (size_t i = 0; i < Num; i++) {
		he = herader[i];
		if ((!strcmp((char*)he.Name, ".text") || 

			(he.Characteristics & IMAGE_SCN_CNT_CODE) ||
			(he.Characteristics & IMAGE_SCN_MEM_EXECUTE)) &&
			he.SizeOfRawData > 0x200
			) {
			break;
		}
	}

	if (!(!strcmp((char*)he.Name, ".text") ||
		(he.Characteristics & IMAGE_SCN_CNT_CODE) ||
			(he.Characteristics & IMAGE_SCN_MEM_EXECUTE))) {
		return false;
	}

	if (he.PointerToRawData + he.SizeOfRawData <
		he.PointerToRawData + signatyre_data_len + code_shift) {
		return false;
	}

	memcpy(
		reinterpret_cast<void*>(const_cast<char*>(signatyre_data)),
		(file_data + he.PointerToRawData + code_shift),
		signatyre_data_len);

	return true;
}
Example #2
0
int matching_feature(
	const PHARDCODE hard_code,
	const unsigned int hard_member_number,
	const wchar_t * file_path)
{
	int if_success_index = -1;
	CPeFile pe;
	//auto start_time = clock();
	
	for (size_t i = 0; i < hard_member_number; i++) {
		hard_code[i].if_sign_success = false;
		hard_code[i].if_image_success = false;
		hard_code[i].if_filesize_success = false;
		hard_code[i].if_signedtrue_success = false;
	}

	auto st_size = get_file_data(file_path, nullptr);
	if (!st_size){
		return if_success_index;
	}

	auto file_data = new char[st_size];
	if (!get_file_data(file_path, file_data)){
		return if_success_index;
	}

	auto if_openfile_success = pe.Attach(file_path);
	if (if_openfile_success == 0UL || 
		if_openfile_success == 1UL || 
		if_openfile_success == 2UL){
		return if_success_index;
	}
	
	for (size_t i = 0; i < hard_member_number; i++) {
		if (!hard_code[i].file_size_end || 
			(hard_code[i].file_size_start < st_size && 
			hard_code[i].file_size_end > st_size)) {
			hard_code[i].if_filesize_success = true;
		}
	}

	if_success_index = search_feature(
		hard_code,
		hard_member_number,
		&pe,
		file_data);

	delete file_data;
	return if_success_index;
}
Example #3
0
static ERL_NIF_TERM close_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
    enum efile_state_t previous_state;
    efile_data_t *d;

    ASSERT(argc == 1);
    if(!get_file_data(env, argv[0], &d)) {
        return enif_make_badarg(env);
    }

    previous_state = erts_atomic32_cmpxchg_acqb(&d->state,
        EFILE_STATE_CLOSED, EFILE_STATE_IDLE);

    if(previous_state == EFILE_STATE_IDLE) {
        posix_errno_t error;

        enif_demonitor_process(env, d, &d->monitor);

        if(!efile_close(d, &error)) {
            return posix_error_to_tuple(env, error);
        }

        return am_ok;
    } else {
        /* CLOSE_PENDING should be impossible at this point since it requires
         * a transition from BUSY; the only valid state here is CLOSED. */
        ASSERT(previous_state == EFILE_STATE_CLOSED);

        return posix_error_to_tuple(env, EINVAL);
    }
}
Example #4
0
bool CFileProducer::produceProcess()
{
    QString szFormat = get_file_data(HANDLER_FILE_FORMAT);
    QString szResult = subset(szFormat, "ssss", m_szMainName);
    m_szFileData += szResult;
    return true;
}
Example #5
0
int fexec_sp(char* filename){
	if(!is_file(filename))
		return -1;

	void (*code)() = (void*) get_file_data(filename);
	(*code)();

	return 0;
}
Example #6
0
void fprint(char* filename){
	if(!is_file(filename))
		return;

	unsigned int i;
	for(i = 0; i < get_file_size(filename); i++)
		vga_putc((char) get_file_data(filename)[i]);

	vga_putc('\n');
}
Example #7
0
json_t *get_json_obj(char file_location[]) {
  char *json_data;
  json_t *root;
  json_error_t error;

  json_data = get_file_data(file_location);
  root = json_loads(json_data, 0, &error);

  return root;
}
Example #8
0
/* This is a special close operation used by the erts_prim_file process for
 * cleaning up orphaned files. It differs from the ordinary close_nif in that
 * it only works for files that have already entered the CLOSED state. */
static ERL_NIF_TERM delayed_close_nif(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
    posix_errno_t ignored;
    efile_data_t *d;

    ASSERT(argc == 1);
    if(!get_file_data(env, argv[0], &d)) {
        return enif_make_badarg(env);
    }

    ASSERT(erts_atomic32_read_acqb(&d->state) == EFILE_STATE_CLOSED);
    efile_close(d, &ignored);

    return am_ok;
}
Example #9
0
static ERL_NIF_TERM file_handle_wrapper(file_op_impl_t operation, ErlNifEnv *env,
        int argc, const ERL_NIF_TERM argv[]) {

    efile_data_t *d;

    enum efile_state_t previous_state;
    ERL_NIF_TERM result;

    if(argc < 1 || !get_file_data(env, argv[0], &d)) {
        return enif_make_badarg(env);
    }

    previous_state = erts_atomic32_cmpxchg_acqb(&d->state,
        EFILE_STATE_BUSY, EFILE_STATE_IDLE);

    if(previous_state == EFILE_STATE_IDLE) {
        result = operation(d, env, argc - 1, &argv[1]);

        previous_state = erts_atomic32_cmpxchg_relb(&d->state,
            EFILE_STATE_IDLE, EFILE_STATE_BUSY);

        ASSERT(previous_state != EFILE_STATE_IDLE);

        if(previous_state == EFILE_STATE_CLOSE_PENDING) {
            /* This is the only point where a change from CLOSE_PENDING is
             * possible, and we're running synchronously, so we can't race with
             * anything else here. */
            posix_errno_t ignored;

            erts_atomic32_set_acqb(&d->state, EFILE_STATE_CLOSED);
            efile_close(d, &ignored);
        }
    } else {
        /* CLOSE_PENDING should be impossible at this point since it requires
         * a transition from BUSY; the only valid state here is CLOSED. */
        ASSERT(previous_state == EFILE_STATE_CLOSED);

        result = posix_error_to_tuple(env, EINVAL);
    }

    return result;
}
Example #10
0
std::vector<char> get_write_data(size_t length)
{
    if(!header_end)
    {
        header_end=true;
		if(data.empty())
            this->is_end=true;

        return std::vector<char>(header.begin(),header.end());
    }else
    {
        if(is_file)
        {
            return get_file_data(length);
        }
        else
        {
            return get_char_data(length);
        }
    }
}
Example #11
0
/* call to check the buffer contents for file reading. move the client
 * to right place in the queue at end of file else repeat file if queue
 * is not ready yet.
 */
int format_check_file_buffer (source_t *source, client_t *client)
{
    refbuf_t *refbuf = client->refbuf;

    if (refbuf == NULL)
    {
        /* client refers to no data, must be from a move */
        if (source->client->con)
        {
            find_client_start (source, client);
            return -1;
        }
        /* source -> file fallback, need a refbuf for data */
        refbuf = refbuf_new (PER_CLIENT_REFBUF_SIZE);
        client->refbuf = refbuf;
        client->pos = refbuf->len;
        client->intro_offset = 0;
    }
    if (client->pos == refbuf->len)
    {
        if (get_file_data (source->intro_file, client))
        {
            client->pos = 0;
            client->intro_offset += refbuf->len;
        }
        else
        {
            if (source->stream_data_tail)
            {
                /* better find the right place in queue for this client */
                client_set_queue (client, NULL);
                find_client_start (source, client);
            }
            else
                client->intro_offset = 0;  /* replay intro file */
            return -1;
        }
    }
    return 0;
}
Example #12
0
int main() {
    uint8_t* data;
    load_result_t result;
    struct image_params img;
    int size;
    
    data = get_file_data("./mach-o-sample", &size);
    
    printf("Size: %d\n", size);
    
    img.ip_vp = data;
    img.ip_vp_size = size;
    img.ip_arch_offset = 0;
    img.ip_arch_size = size;
    img.ip_vdata = data;
    
    hexdump(data, 100, 0);
    
    load_machfile(&img, data, &result);
    
    return 0;
}
Example #13
0
void* pref_main (void* arg) {
	int thread_id = *((int*)arg);
	free(arg);
	while (1) {
		char guess[MAX_REQUEST]; // Buffer for guessed filename
		int size = 0;

		void* item = queue_consume( &prefetch_queue );
		
		// this happens only if queue_consume_all() was called and no items remain.
		if( item == (void*)-1 ) {
			printf( "Prefetcher exiting.\n" );
			pthread_exit( (void*)NULL );
		}
		
		request_t* req = (request_t*)item;

		if (nextguess(req->filename, guess) != 0) { 
			fprintf(stderr, "Prefetcher failed to get next guess\n");
			fprintf(stderr, " --filename: %s\n", req->filename );
			fprintf(stderr, " --guess: %s\n", guess );
		} else {
			// try to get the cache entry for the guess. if it isn't there
			// then put it there.
			char* data;
			if (get_cache(guess, &data) == -1) {
				size = get_file_data(guess, &data);
				put_cache(guess, data, size);
			}
		}

		// free request created by dispatch.
		free( req->filename );
		free( req );
			
	}

}
Example #14
0
uint32_t pe_load_library(uint8_t *file_path){
	uint32_t                 file_size;
	uint32_t                 sections_offset;
	uint32_t                 x;
	uint8_t                 *file_data;
	uint8_t                 *mapped_data;
	PE_IMAGE_DOS_HEADER     *dos;
	PE_IMAGE_NT_HEADERS     *nt;
	PE_IMAGE_SECTION_HEADER *sections;

	file_size = get_file_size(file_path);
	if(file_size == 0) return 0;

	file_data = safe_malloc(file_size);
	if(get_file_data(file_path, file_data, file_size, 0) == 1){
		free(file_data);
		return 0;
	}

	dos = (PE_IMAGE_DOS_HEADER*)file_data;
	if(dos->e_magic != DOS_HEADER_MAGIC){
		free(file_data);
		return 0;
	}

	nt = (PE_IMAGE_NT_HEADERS*)(file_data + dos->e_lfanew);
	if(nt->Signature != PE_NT_HEADER_SIGNATURE_PE){
		free(file_data);
		return 0;
	}

	if(nt->OptionalHeader.Magic != PE_IMAGE_NT_OPTIONAL_HDR32_MAGIC){
		free(file_data);
		return 0;
	}

	if(nt->FileHeader.NumberOfSections == 0){
		free(file_data);
		return 0;
	}
	sections_offset = nt->FileHeader.SizeOfOptionalHeader + dos->e_lfanew + PE_SIZE_OF_NT_SIGNATURE + PE_IMAGE_SIZEOF_FILE_HEADER;
	sections = (PE_IMAGE_SECTION_HEADER *)(file_data + sections_offset);

	file_size = sections[nt->FileHeader.NumberOfSections - 1].VirtualAddress 
			  + sections[nt->FileHeader.NumberOfSections - 1].Misc.VirtualSize;
	if((file_size % nt->OptionalHeader.SectionAlignment) != 0)
		file_size += nt->OptionalHeader.SectionAlignment - (file_size % nt->OptionalHeader.SectionAlignment);

	//Allocate new memory and copy PE headers over.
	mapped_data = safe_malloc(file_size);
	memcpy(mapped_data, file_data, sections_offset + (PE_IMAGE_SIZEOF_SECTION_HEADER * nt->FileHeader.NumberOfSections));

	dos = (PE_IMAGE_DOS_HEADER*)mapped_data;
	nt  = (PE_IMAGE_NT_HEADERS*)(mapped_data + dos->e_lfanew);
	sections = (PE_IMAGE_SECTION_HEADER *)(mapped_data + sections_offset);
	for(x = 0; x < nt->FileHeader.NumberOfSections; x++){
		//Copy sections over
		memset(mapped_data + sections[x].VirtualAddress, 0, sections[x].Misc.VirtualSize); 
		memcpy(mapped_data + sections[x].VirtualAddress, file_data + sections[x].PointerToRawData, 
			(sections[x].SizeOfRawData > sections[x].Misc.VirtualSize ? 
			 sections[x].Misc.VirtualSize : sections[x].SizeOfRawData));
	}

	free(file_data);    

	return (uint32_t)mapped_data;
}
Example #15
0
int kernel_run_bch_ber_ch_mode
(
	int galois_field_degree,
	int bch_code_length,
	int error_correction,
	int decoded_seq_buf_size_frames,
	double ber,
	char* out_file_postfix,
	char* input_file_name,
	int gui_progress
)
{
	FILE* flog = stdout;
	log(flog, "Current mode: use of BCH codec only via BER parametrized channel\n");
	log(flog, "Simulation kernel settings:\n");
	log(flog, "Galois field degree: %d\n",							galois_field_degree);
	log(flog, "BCH code length: %d\n",								bch_code_length);
	log(flog, "Error correction property: %d\n",					error_correction);
	log(flog, "BER (Bit Error Rate): %.2f\n",						ber);
	log(flog, "Output file postfix: %s\n",							out_file_postfix);
	log(flog, "Input file name: %s\n",								input_file_name);

	/************************************************************************/
	/* Параметры тестового окружения.                                       */
	/************************************************************************/
	char* file_path = input_file_name;
	int* data_in = get_file_data(file_path);
	int data_size = get_file_size(file_path) * CHAR_BIT;
	//print_data(data_in, data_size);
	int* data_out = NULL;

	/************************************************************************/
	/* Параметры БЧХ-кодера                                                 */
	/************************************************************************/
	//int galois_field_degree = 4;
	//int bch_code_length = 15;
	//int error_correction = 3;

	/************************************************************************/
	/* Параметры ДСК-канала                                                 */
	/************************************************************************/
	//double ber = 0;//2*1e-5;
	int random_errors_quantity = 5;
	int erase_errors_quantity = 2;

	/************************************************************************/
	/* Создание программных компонентов.                                    */
	/************************************************************************/
	bch_encoder_t bch_encoder = bch_encoder_create(flog, galois_field_degree, bch_code_length, error_correction);
	bch_decoder_t bch_decoder = bch_decoder_create(ERRORS_CORRECTION_MODE, flog, galois_field_degree, bch_code_length, error_correction);

	/* Получение длины фрейма данных, который может кодировать БЧХ-кодер. */
	int bch_frame_size = bch_encoder_get_frame_size(bch_encoder);
	int bch_codeword_size = bch_encoder_get_codeword_size(bch_encoder);

	/************************************************************************/
	/* Создание программных компонентов.                                    */
	/************************************************************************/
	transmitter_t transmitter = transmitter_create(flog, bch_frame_size, data_in, data_size);
	receiver_t receiver = receiver_create(flog, bch_frame_size, data_size);

	/************************************************************************/
	/* Создание программных компонентов.                                    */
	/************************************************************************/
	channel_bs_t channel_bs = channel_bs_create(flog, ber);

	/************************************************************************/
	/* Параметры промежуточных буферов                                      */
	/************************************************************************/
	int bch_frame_fifo_size = decoded_seq_buf_size_frames + 1;
	int bch_codeword_fifo_size = decoded_seq_buf_size_frames + 1;

	/************************************************************************/
	/* Создание промежуточных буферов.                                      */
	/************************************************************************/
	frame_fifo_t bch_frame_fifo = frame_fifo_create(bch_frame_fifo_size, bch_frame_size);
	codeword_fifo_t bch_codeword_fifo = codeword_fifo_create(bch_codeword_fifo_size, bch_codeword_size);

	/************************************************************************/
	/* Запуск программных компонентов.                                      */
	/************************************************************************/
	log(flog, "Simulation started\n");
	transmitter->start(transmitter);
	receiver->start(receiver);
	bch_encoder->start(bch_encoder);
	bch_decoder->start(bch_decoder);
	channel_bs->start(channel_bs);

	/************************************************************************/
	/* Запуск цикла моделирования.                                          */
	/************************************************************************/
	int sent_frames = 0;
	int frames_to_sent = data_size/bch_frame_size;
	int send_bits_all = data_size+decoded_seq_buf_size_frames*bch_frame_size;
L_Loop:
	/*if (!(sent_bits_cnt % percent_precision) && !gui_progress)
		printf("\rProgress: %.0f%%", ((float)sent_bits_cnt/
		(float)send_bits_all) * 100);
	else if (!(sent_bits_cnt % percent_precision))
		printf("Progress: %.0f%%\n", ((float)sent_bits_cnt/
		(float)send_bits_all) * 100);*/
	loadbar(sent_frames++, frames_to_sent, 50);

	/* Генерация фрейма данных передатчиком. */
	frame_t bch_frame_in = transmitter->transmit_frame(transmitter);
	if (bch_frame_in == NULL) goto L_Stop;

	frame_display(bch_frame_in);

	/* Запись сгенерированного кодового слова БЧХ-кода в промежуточный буфер. */
	bch_frame_fifo = frame_fifo_put(bch_frame_fifo, bch_frame_in);

	/* Кодирование фрейма данных БЧХ-кодером и получение кодового слова БЧХ-кода. */
	codeword_t bch_codeword_in = bch_encoder->encode(bch_encoder, bch_frame_in);
	codeword_display(bch_codeword_in);

	/* Передача кодового слова сверточного кода по каналу. */
	codeword_t bch_codeword_out = channel_bs->transfer(channel_bs, bch_codeword_in);

	/* Декодирование кодового слова БЧХ-декодером и получение фрейма данных. */
	frame_t bch_frame_out = bch_decoder->decode(bch_decoder, bch_codeword_out, bch_codeword_in);
	frame_display(bch_frame_out);

	/* Извлечение из промежуточного буфера фрейма данных. */
	bch_frame_in = frame_fifo_get(bch_frame_fifo);

	/* Прием фрейма данных и анализ его корректности. */
	receiver->receive_frame(receiver, bch_frame_out, bch_frame_in);

	goto L_Loop;

	/************************************************************************/
	/* Останов программных компонентов.                                     */
	/************************************************************************/
L_Stop:
	transmitter->stop(transmitter);
	receiver->stop(receiver);
	bch_encoder->stop(bch_encoder);
	bch_decoder->stop(bch_decoder);
	channel_bs->stop(channel_bs);
	log(flog, "Simulation stopped\n");

	/************************************************************************/
	/* Проверка корректности принятых данных.                               */
	/************************************************************************/
	data_out = receiver_get_received_data(receiver);
	
	printf("\n");
	if (cmp_data(data_in, data_out, data_size))
		printf("Comparison test: OK\n");
	else
		printf("Comparison test: FAIL\n");

	free(data_in);

	out_file_postfix = extend_out_file_postfix(
		out_file_postfix,
		galois_field_degree,
		bch_code_length,
		error_correction,
		0,
		ber);
	put_file_data(data_out, file_path, out_file_postfix);

	//print_data(data_in, data_size);
	//print_data(data_out, data_size);

	/************************************************************************/
	/* Уничтожение программных компонентов.                                 */
	/************************************************************************/
	transmitter_destroy(transmitter);
	receiver_destroy(receiver);
	bch_encoder_destroy(bch_encoder);
	bch_decoder_destroy(bch_decoder);
	channel_bs_destroy(channel_bs);
	frame_fifo_destroy(bch_frame_fifo);
	codeword_fifo_destroy(bch_codeword_fifo);
#ifdef _DEBUG	
	_CrtDumpMemoryLeaks();
#endif
	return 0;
}
Example #16
0
int kernel_run_cnv_mode
	(
	int galois_field_degree,
	int bch_code_length,
	int error_correction,
	int decoded_seq_buf_size_frames,
	double ber,
	char* out_file_postfix,
	char* input_file_name,
	int gui_progress)
{
	FILE* flog = stdout;
	log(flog, "Current mode: use of CNV codec only via BER parametrized channel\n");
	log(flog, "Simulation kernel settings:\n");
	log(flog, "Galois field degree: %d\n",							galois_field_degree);
	log(flog, "BCH code length: %d\n",								bch_code_length);
	log(flog, "Error correction property: %d\n",					error_correction);
	log(flog, "Size of decoded buffer (CNV decoder): %d\n",			decoded_seq_buf_size_frames);
	log(flog, "BER (Bit Error Rate): %.2f\n",						ber);
	log(flog, "Output file postfix: %s\n",							out_file_postfix);
	log(flog, "Input file name: %s\n",								input_file_name);

	/************************************************************************/
	/* Параметры тестового окружения.                                       */
	/************************************************************************/
	int* data_in = get_file_data(input_file_name);
	int data_size = get_file_size(input_file_name) * CHAR_BIT;
	//print_data(data_in, data_size);
	int* data_out = NULL;

	int use_bch_codec = 0;

	/************************************************************************/
	/* Параметры ДСК-канала                                                 */
	/************************************************************************/
	//double ber = 0;//2*1e-5;

	/************************************************************************/
	/* Технологические переменные.                                          */
	/************************************************************************/
	int skip_q_cnt = 0;
	int percent_precision = gui_progress ? (int)1e3 : 5;
	int sent_bits_cnt = 0;

	/************************************************************************/
	/* Создание программных компонентов.                                    */
	/************************************************************************/
	int frame_size = 10;
	transmitter_t transmitter = transmitter_create(flog, frame_size, data_in, data_size);
	receiver_t receiver = receiver_create(flog, frame_size, data_size);

	/************************************************************************/
	/* Параметры сверточного кодера.                                        */
	/************************************************************************/
	int regs_q = 2; /* ! do not change */
	int codeword_length = frame_size * regs_q;
	//int decoded_seq_buf_size_frames = 2;
	int decoded_seq_buf_size = frame_size * decoded_seq_buf_size_frames + 1;
	int skip_q = decoded_seq_buf_size_frames;

	/************************************************************************/
	/* Создание программных компонентов.                                    */
	/************************************************************************/
	cnv_encoder_t cnv_encoder = cnv_encoder_create(flog, regs_q, codeword_length);
	cnv_decoder_t cnv_decoder = cnv_decoder_create(flog, regs_q, decoded_seq_buf_size);

	/************************************************************************/
	/* Создание программных компонентов.                                    */
	/************************************************************************/
	channel_bs_t channel_bs = channel_bs_create(flog, ber);

	/************************************************************************/
	/* Параметры промежуточных буферов                                      */
	/************************************************************************/
	int frame_fifo_size = decoded_seq_buf_size_frames + 1;

	/************************************************************************/
	/* Создание промежуточных буферов.                                      */
	/************************************************************************/
	frame_fifo_t frame_fifo = frame_fifo_create(frame_fifo_size, frame_size);

	/************************************************************************/
	/* Запуск программных компонентов.                                      */
	/************************************************************************/
	log(flog, "Simulation started\n");
	transmitter->start(transmitter);
	receiver->start(receiver);
	cnv_encoder->start(cnv_encoder);
	cnv_decoder->start(cnv_decoder);
	channel_bs->start(channel_bs);

	/************************************************************************/
	/* Запуск цикла моделирования.                                          */
	/************************************************************************/
	int sent_frames = 0;
	int frames_to_sent = data_size/frame_size;
	int send_bits_all = data_size+decoded_seq_buf_size_frames*frame_size;
L_Loop:
	/*if (!(sent_bits_cnt % percent_precision) && !gui_progress)
		printf("\rProgress: %.0f%%", ((float)sent_bits_cnt/
		(float)send_bits_all) * 100);
	else if (!(sent_bits_cnt % percent_precision))
		printf("Progress: %.0f%%\n", ((float)sent_bits_cnt/
		(float)send_bits_all) * 100);*/
	loadbar(sent_frames++, frames_to_sent, 50);
	sent_bits_cnt += frame_size;

	/* Генерация фрейма данных передатчиком. */
	frame_t frame_in = transmitter->transmit_frame(transmitter);
	if (frame_in == NULL) goto L_Dummy_Generation;

	frame_display(frame_in);

	/* Запись сгенерированного фрейма данных в промежуточный буфер. */
	frame_fifo = frame_fifo_put(frame_fifo, frame_in);
	
	/* Кодирование фрейма данных сверточным кодером и получение кодового слова сверточного кода.*/
	codeword_t cnv_codeword_in = cnv_encoder->encode(cnv_encoder, frame_in);
	goto L_Skip_Dummy_Generation;

L_Dummy_Generation:
	cnv_codeword_in = codeword_create(cnv_encoder->codeword_length);

L_Skip_Dummy_Generation:
	codeword_display(cnv_codeword_in);

	/* Передача кодового слова сверточного кода по каналу. */
	codeword_t cnv_codeword_out = channel_bs->transfer(channel_bs, cnv_codeword_in);
	codeword_display(cnv_codeword_out);	

	/* Декодирование кодового слова сверточного кода и получение фрейма данных. */
	frame_t frame_out = cnv_decoder->decode(cnv_decoder, cnv_codeword_out, cnv_codeword_in);
	frame_display(frame_out);

	/* Проверка счетчика пропусков. */
	if(skip_q_cnt != skip_q) { 
		skip_q_cnt++; 
		goto L_Loop;
	}

	/* Извлечение из промежуточного буфера фрейма данных. */
	frame_in = frame_fifo_get(frame_fifo);
	frame_display(frame_in);

	/* Прием фрейма данных и анализ его корректности. */
	receiver->receive_frame(receiver, frame_out, frame_in);

	/* Проверка наличия фреймов в буфере. */
	if(frame_fifo_is_empty(frame_fifo))
		goto L_Stop;
	else 
		goto L_Loop;

	/************************************************************************/
	/* Останов программных компонентов.                                     */
	/************************************************************************/
L_Stop:
	transmitter->stop(transmitter);
	receiver->stop(receiver);
	cnv_encoder->stop(cnv_encoder);
	cnv_decoder->stop(cnv_decoder);
	channel_bs->stop(channel_bs);
	log(flog, "Simulation stopped\n");

	/************************************************************************/
	/* Проверка корректности принятых данных.                               */
	/************************************************************************/
	data_out = receiver_get_received_data(receiver);
	
	printf("\n");
	if (cmp_data(data_in, data_out, data_size))
		printf("Comparison test: OK\n");
	else
		printf("Comparison test: FAIL\n");

	free(data_in);

	out_file_postfix = extend_out_file_postfix(
		out_file_postfix,
		galois_field_degree,
		bch_code_length,
		error_correction,
		decoded_seq_buf_size,
		ber);
	put_file_data(data_out, input_file_name, out_file_postfix);

	//print_data(data_in, data_size);
	//print_data(data_out, data_size);

	/************************************************************************/
	/* Уничтожение программных компонентов.                                 */
	/************************************************************************/
	transmitter_destroy(transmitter);
	receiver_destroy(receiver);
	cnv_encoder_destroy(cnv_encoder);
	cnv_decoder_destroy(cnv_decoder);
	channel_bs_destroy(channel_bs);
	frame_fifo_destroy(frame_fifo);
#ifdef _DEBUG	
	_CrtDumpMemoryLeaks();
#endif
	return 0;
}
Example #17
0
/*
 * This routine exists to support the load_dylinker().
 *
 * This routine has its own, separate, understanding of the FAT file format,
 * which is terrifically unfortunate.
 */
static
load_return_t
get_macho_vnode(
	char			*path,
	integer_t		archbits,
	struct mach_header	*mach_header,
	off_t			*file_offset,
	off_t			*macho_size,
	struct macho_data	*data,
	uint8_t		**vpp
)
{
    /*uint8_t* data_f = get_file_data(path, macho_size);
    *vpp = data_f;
    *file_offset = 0;
    *mach_header = *(struct mach_header*)(data_f);
    data->__header.mach_header = *mach_header;
    
    return LOAD_SUCCESS;*/
    
	uint8_t		*vp;
	boolean_t		is_fat;
	struct fat_arch		fat_arch;
	int			error = LOAD_SUCCESS;
	int resid;
	union macho_vnode_header *header = &data->__header;
	off_t fsize = (off_t)0;

	/*
	 * Capture the kernel credential for use in the actual read of the
	 * file, since the user doing the execution may have execute rights
	 * but not read rights, but to exec something, we have to either map
	 * or read it into the new process address space, which requires
	 * read rights.  This is to deal with lack of common credential
	 * serialization code which would treat NOCRED as "serialize 'root'".
	 */

    int file_size;
    vp = get_file_data(path, &file_size);
    
    header = (union macho_vnode_header*)vp;
    
	if (header->mach_header.magic == MH_MAGIC ||
	    header->mach_header.magic == MH_MAGIC_64) {
		is_fat = FALSE;
	} else if (header->fat_header.magic == FAT_MAGIC ||
	    header->fat_header.magic == FAT_CIGAM) {
		is_fat = TRUE;
	} else {
		error = LOAD_BADMACHO;
        printf("get_macho_vnode 1: %s:", load_to_string(error));
		goto bad2;
	}

    printf("Is fat: %d\n", is_fat);
	if (is_fat) {
		/* Look up our architecture in the fat file. */
		error = fatfile_getarch_with_bits(vp, archbits,
		    (vm_offset_t)(&header->fat_header), &fat_arch);
        if (error != LOAD_SUCCESS) {
            printf("get_macho_vnode 2: %s\n", load_to_string(error));
			goto bad2;
        }

        printf("get_macho_vnode 2: fat_arch.offset = %d\n", fat_arch.offset);
        header = (vp + fat_arch.offset);
        
		/* Is this really a Mach-O? */
		if (header->mach_header.magic != MH_MAGIC &&
		    header->mach_header.magic != MH_MAGIC_64) {
			error = LOAD_BADMACHO;
            printf("get_macho_vnode 3: %s\n", load_to_string(error));
			goto bad2;
		}

		*file_offset = fat_arch.offset;
		*macho_size = fat_arch.size;
	} else {
		/*
		 * Force get_macho_vnode() to fail if the architecture bits
		 * do not match the expected architecture bits.  This in
		 * turn causes load_dylinker() to fail for the same reason,
		 * so it ensures the dynamic linker and the binary are in
		 * lock-step.  This is potentially bad, if we ever add to
		 * the CPU_ARCH_* bits any bits that are desirable but not
		 * required, since the dynamic linker might work, but we will
		 * refuse to load it because of this check.
		 */
		if ((cpu_type_t)(header->mach_header.cputype & CPU_ARCH_MASK) != archbits) {
			error = LOAD_BADARCH;
			goto bad2;
		}

		*file_offset = 0;
		*macho_size = fsize;
	}

	*mach_header = header->mach_header;
	*vpp = vp;

    printf("get_macho_vnode 4: %s\n", load_to_string(error));
    
	return (error);

bad2:
bad1:
	return(error);
}
Example #18
0
/*****************************************************************************
 Read a single log file.
 *****************************************************************************/
void file_read(int fd, short int flnm, char *fnam, FILE *strm,
	       const geoid_height_t *gdhtp, const status_t* status,
	       const cmdlnopts_t *cmdopt) {
  logfile_t lgfl;
#if !defined(FILENAME_DATE_PTR)
  date_time_t dt;
#endif
  gps_fix_t *gfxp = NULL;
  float *gcrp = NULL;
  char *pstr = "";
  int fn;

  if (cmdopt->vflg)
    printf("Requesting metadata for file %4d\n", flnm);

  /* Read metadata for file number flnm */
  if (get_file_info(fd, flnm, &lgfl) < 0) {
    fprintf(stderr,"rtkgps: Error reading information for file %d [%s]\n",
	    flnm, gcstrerror(rcerrno));
    free(fnam);
    outlog_enable(fd, status->gpsms, cmdopt);
    coms_close(fd, cmdopt);
    exit(5);
  }

  /* If memory is allocated for the file name, the output path is a
      destination directory. Construct a standard file path with the
      directory as a base, and open the file for writing */
  if (fnam != NULL) {

#if !defined(FILENAME_DATE_PTR)
    if (get_file_start_time(fd, &lgfl, &dt) != 1) {
      fprintf(stderr,"rtkgps: Error reading initial time for file %d [%s]\n",
	      flnm, gcstrerror(rcerrno));
      free(fnam);
      outlog_enable(fd, status->gpsms, cmdopt);
      coms_close(fd, cmdopt);
      exit(5);
    }
#endif

    /* Add filename postfix to indicate file is not complete (data
       still being captured). */
    if (flnm == status->nfile-1)
      pstr = "_part";
    /* Construct file name */
#if defined(FILENAME_DATE_PTR)
    sprintf(fnam, "%s/%8.8s_%06x%s.%s", cmdopt->dsts, lgfl.date, 
	    lgfl.memp, pstr, (cmdopt->nflg)?"rngl":"nmea");
#else
    sprintf(fnam, "%s/%8.8sT%6.6sZ%s.%s", cmdopt->dsts, lgfl.date, 
	    dt.time, pstr, (cmdopt->nflg)?"rngl":"nmea");
#endif
    /* Skip existing files if requested */
    if (cmdopt->uflg && is_nzsregfile(fnam) && flnm != status->nfile-1) {
      if (cmdopt->vflg)
	printf("Skipping download for file %4d\n", flnm);
      return;
    }

    /* Create backup of output file if it already exists */
    if (file_backup(fnam) != 0) {
      fprintf(stderr,"rtkgps: Error creating backup of file %s\n", fnam);
      free(fnam);
      outlog_enable(fd, status->gpsms, cmdopt);
      coms_close(fd, cmdopt);
      exit(3);
    }
    /* Attempt to open file */
    if ((strm = fopen(fnam, "w")) == NULL) {
      fprintf(stderr,"rtkgps: Error opening output file %s [%s]\n",
	      fnam, gcstrerror(rcerrno));
      free(fnam);
      outlog_enable(fd, status->gpsms, cmdopt);
      coms_close(fd, cmdopt);
      exit(3);
    }
  }

  /* Allocate memory for the log file data */
  if ((gfxp = malloc(lgfl.nfix*sizeof(gps_fix_t))) == NULL) {
    fprintf(stderr,"rtkgps: Error allocating memory\n");
    free(fnam);
    if (fnam != NULL)
      fclose(strm);
    outlog_enable(fd, status->gpsms, cmdopt);
    coms_close(fd, cmdopt);
    exit(2);
  }

#ifdef GEOIDCOR
  /* If necessary, allocate memory for geoid correction values */
  if (lgfl.fxtyp > 0 && gdhtp->filep != NULL) {
    if ((gcrp = malloc(lgfl.nfix*sizeof(float))) == NULL) {
      fprintf(stderr,"rtkgps: Error allocating memory\n");
      free(fnam);
      if (fnam != NULL)
	fclose(strm);
      outlog_enable(fd, status->gpsms, cmdopt);
      coms_close(fd, cmdopt);
      exit(2);
    }
  }
#endif

  if (cmdopt->vflg)
    printf("Requesting content of file   %4d\n", flnm);

  /* Read the log file data */
  fn = get_file_data(fd, &lgfl, gfxp);
  if (fn < 0) {
    fprintf(stderr,"rtkgps: Error reading file %d [%s]\n",
	    flnm, gcstrerror(rcerrno));
    /* Remove empty file so that it isn't skipped (with -u flag) on
       read restart */
    if (fnam != NULL)
      remove(fnam);
    free(gcrp);
    free(gfxp);
    free(fnam);
    if (fnam != NULL)
      fclose(strm);
    outlog_enable(fd, status->gpsms, cmdopt);
    coms_close(fd, cmdopt);
    exit(5);
  }

#ifdef GEOIDCOR
  if (gcrp != NULL) {
    const double dgrd = 360.0/(2*M_PI);
    unsigned short n;

    if (cmdopt->vflg)
      printf("Computing geoid altitude corrections\n");
    for (n = 0; n < lgfl.nfix; n++) {
      gcrp[n] = geoid_calc_correction(gdhtp, dgrd*gfxp[n].lat,
				      dgrd*gfxp[n].lng);
    }
  }
#endif

  /* Print the log file data to the output stream */
  if (cmdopt->nflg) {
    if (fnam != NULL)
      print_hdr_native(strm);
    print_log_native(strm, &lgfl, gfxp, gcrp);
  }
  else {
    if (fnam != NULL)
      print_hdr_nmea(strm, cmdopt->btas);
    print_log_nmea(strm, &lgfl, gfxp, gcrp);
  }

  /* Free memory for geoid correction values */
  free(gcrp);
  /* Free memory for the log file data */
  free(gfxp);

  /* If memory is allocated for the file name, the output path is a
     directory and the output stream was opened in this function, so
     the stream should be closed here */
  if (fnam != NULL)
    fclose(strm);
}
 FileData get_asset_data(std::string relative_path) {
     assert(!relative_path.empty());
     return get_file_data(relative_path);
 }
Example #20
0
int process_file(FILE *data_file, FILE *struct_file, const char *filename)
{
  char varname[MAX_PATH_LEN];
  int i = 0;
  char qualifiedName[MAX_PATH_LEN];
  int file_size;
  u16_t http_hdr_chksum = 0;
  u16_t http_hdr_len = 0;
  int chksum_count = 0;
  u8_t flags = 0;
  const char* flags_str;
  u8_t has_content_len;
  u8_t* file_data;
  int is_compressed = 0;

  /* create qualified name (@todo: prepend slash or not?) */
  sprintf(qualifiedName,"%s/%s", curSubdir, filename);
  /* create C variable name */
  strcpy(varname, qualifiedName);
  /* convert slashes & dots to underscores */
  fix_filename_for_c(varname, MAX_PATH_LEN);
  register_filename(varname);
#if ALIGN_PAYLOAD
  /* to force even alignment of array, type 1 */
  fprintf(data_file, "#if FSDATA_FILE_ALIGNMENT==1" NEWLINE);
  fprintf(data_file, "static const " PAYLOAD_ALIGN_TYPE " dummy_align_%s = %d;" NEWLINE, varname, payload_alingment_dummy_counter++);
  fprintf(data_file, "#endif" NEWLINE);
#endif /* ALIGN_PAYLOAD */
  fprintf(data_file, "static const unsigned char FSDATA_ALIGN_PRE data_%s[] FSDATA_ALIGN_POST = {" NEWLINE, varname);
  /* encode source file name (used by file system, not returned to browser) */
  fprintf(data_file, "/* %s (%d chars) */" NEWLINE, qualifiedName, strlen(qualifiedName)+1);
  file_put_ascii(data_file, qualifiedName, strlen(qualifiedName)+1, &i);
#if ALIGN_PAYLOAD
  /* pad to even number of bytes to assure payload is on aligned boundary */
  while(i % PAYLOAD_ALIGNMENT != 0) {
    fprintf(data_file, "0x%02.2x,", 0);
    i++;
  }
#endif /* ALIGN_PAYLOAD */
  fprintf(data_file, NEWLINE);

  has_content_len = !is_ssi_file(filename);
  file_data = get_file_data(filename, &file_size, includeHttpHeader && has_content_len, &is_compressed);
  if (includeHttpHeader) {
    file_write_http_header(data_file, filename, file_size, &http_hdr_len, &http_hdr_chksum, has_content_len, is_compressed);
    flags = FS_FILE_FLAGS_HEADER_INCLUDED;
    if (has_content_len) {
      flags |= FS_FILE_FLAGS_HEADER_PERSISTENT;
    }
  }
  if (precalcChksum) {
    chksum_count = write_checksums(struct_file, varname, http_hdr_len, http_hdr_chksum, file_data, file_size);
  }

  /* build declaration of struct fsdata_file in temp file */
  fprintf(struct_file, "const struct fsdata_file file_%s[] = { {" NEWLINE, varname);
  fprintf(struct_file, "file_%s," NEWLINE, lastFileVar);
  fprintf(struct_file, "data_%s," NEWLINE, varname);
  fprintf(struct_file, "data_%s + %d," NEWLINE, varname, i);
  fprintf(struct_file, "sizeof(data_%s) - %d," NEWLINE, varname, i);
  switch(flags)
  {
  case(FS_FILE_FLAGS_HEADER_INCLUDED):
     flags_str = "FS_FILE_FLAGS_HEADER_INCLUDED";
     break;
  case(FS_FILE_FLAGS_HEADER_PERSISTENT):
     flags_str = "FS_FILE_FLAGS_HEADER_PERSISTENT";
     break;
  case(FS_FILE_FLAGS_HEADER_INCLUDED | FS_FILE_FLAGS_HEADER_PERSISTENT):
     flags_str = "FS_FILE_FLAGS_HEADER_INCLUDED | FS_FILE_FLAGS_HEADER_PERSISTENT";
     break;
  default:
     flags_str = "0";
     break;
  }
  fprintf(struct_file, "%s," NEWLINE, flags_str);
  if (precalcChksum) {
    fprintf(struct_file, "#if HTTPD_PRECALCULATED_CHECKSUM" NEWLINE);
    fprintf(struct_file, "%d, chksums_%s," NEWLINE, chksum_count, varname);
    fprintf(struct_file, "#endif /* HTTPD_PRECALCULATED_CHECKSUM */" NEWLINE);
  }
  fprintf(struct_file, "}};" NEWLINE NEWLINE);
  strcpy(lastFileVar, varname);

  /* write actual file contents */
  i = 0;
  fprintf(data_file, NEWLINE "/* raw file data (%d bytes) */" NEWLINE, file_size);
  process_file_data(data_file, file_data, file_size);
  fprintf(data_file, "};" NEWLINE NEWLINE);
  free(file_data);
  return 0;
}
Example #21
0
uint32_t __stdcall crev_old(uint32_t padd, uint8_t archive_ver, uint8_t *seed, uint8_t *ini_file, uint8_t *ini_header, uint32_t *version, uint32_t *checksum, uint8_t *result){
	uint64_t A = 0;
	uint64_t B = 0;
	uint64_t C = 0;
	uint32_t S = 0;
	uint32_t x = 0;
	uint32_t y = 0;
	uint32_t file_size = 0;
	uint8_t  ops[4];
	uint8_t *files[4];
	uint8_t *buff = safe_malloc(MAX_PATH);
	const uint8_t *keys[] = {"Exe", "Util", "Network"};
	const uint32_t seeds[] = {0xE7F4CB62, 0xF6A14FFC, 0xAA5504AF, 0x871FCDC2, 0x11BF6A18, 0xC57292E6, 0x7927D27E, 0x2FEC8733};

	uint8_t *tok;
	uint8_t *tok_pos;
	//uint8_t *tmp = safe_malloc(MAX_PATH * 2);

	if(archive_ver > 7){
		free(buff);
		return CREV_UNKNOWN_REVISION;
	}

	tok = strtok_s(seed, " ", &tok_pos);
	for(x = 0; x < 3; x++){
		if(tok == NULL)
			return CREV_MALFORMED_SEED;
		if(tok[1] == '='){
			if(tok[0] == 'A' || tok[0] == 'a') A = strtoul((uint8_t*)&tok[2], NULL, 10);
			if(tok[0] == 'B' || tok[0] == 'b') B = strtoul((uint8_t*)&tok[2], NULL, 10);
			if(tok[0] == 'C' || tok[0] == 'c') C = strtoul((uint8_t*)&tok[2], NULL, 10);
		}else{
			return CREV_MALFORMED_SEED;
		}
		tok = strtok_s(NULL, " ", &tok_pos);
	}
	/*
	 *sprintf_s(tmp, MAX_PATH * 2, "A: %lu\n", A); wwrite_to_file(tmp);
	 *sprintf_s(tmp, MAX_PATH * 2, "B: %lu\n", B); wwrite_to_file(tmp);
	 *sprintf_s(tmp, MAX_PATH * 2, "C: %lu\n", C); wwrite_to_file(tmp);
	 */
	
	tok = strtok_s(NULL, " ", &tok_pos); //Skip the '4'

	for(x = 0; x < 4; x++){
		if(tok == NULL)
			return CREV_MALFORMED_SEED;
		ops[x] = tok[3];
		tok[3] = '.';
		switch(x){
			case 0: if(_stricmp(tok, "A=A.S") != 0) return CREV_MALFORMED_SEED; break;
			case 1: if(_stricmp(tok, "B=B.C") != 0) return CREV_MALFORMED_SEED; break;
			case 2: if(_stricmp(tok, "C=C.A") != 0) return CREV_MALFORMED_SEED; break;
			case 3: if(_stricmp(tok, "A=A.B") != 0) return CREV_MALFORMED_SEED; break;
		}
		tok = strtok_s(NULL, " ", &tok_pos);
	}

	//sprintf_s(tmp, MAX_PATH * 2, "Ops: %c%c%c%c\n", ops[0], ops[1], ops[2], ops[3]); wwrite_to_file(tmp);

	read_ini_new(ini_file, ini_header, "Path", "", buff, MAX_PATH);
	files[0] = safe_malloc(MAX_PATH);
	combine_paths(buff, "", files[0], MAX_PATH);

	for(x = 1; x < 4; x++){
		read_ini_new(ini_file, ini_header, (uint8_t*)keys[x-1], "\xFF", buff, MAX_PATH);
		if(buff[0] == 0xFF){
			for(y = 0; y < x; y++)
				if(files[y] != NULL) free(files[y]);
			sprintf_s(result, crev_max_result(), "%s\x00", keys[x-1]);
			return CREV_MISSING_FILENAME;
		}

		if (_stricmp(buff, "NULL") == 0){
			files[x] = NULL;
		}else{
			files[x] = safe_malloc(MAX_PATH);
			combine_paths(files[0], buff, files[x], MAX_PATH);
		}
	}
	free(buff);
	/*
	 *sprintf_s(tmp, MAX_PATH * 2, "Path:    %s\n", files[0]); wwrite_to_file(tmp);
	 *sprintf_s(tmp, MAX_PATH * 2, "Exe:     %s %d\n", files[1], get_file_size(files[1])); wwrite_to_file(tmp);
	 *sprintf_s(tmp, MAX_PATH * 2, "Util:    %s %d\n", files[2], get_file_size(files[2])); wwrite_to_file(tmp);
	 *sprintf_s(tmp, MAX_PATH * 2, "Network: %s %d\n", files[3], get_file_size(files[3])); wwrite_to_file(tmp);
	 */

	A ^= seeds[archive_ver];
	for(x = 1; x < 4; x++){
		if (files[x] == NULL){
			continue;
		}
		file_size = get_file_size(files[x]);
		if((file_size % 1024) != 0){
			if(padd == 1) file_size += (1024 - (file_size % 1024));
			else          file_size -= (file_size % 1024);
		}

		if(file_size == 0){
			sprintf_s(result, CREV_MAX_RESULT, files[x]);
			return CREV_MISSING_FILE;
		}

		buff = safe_malloc(file_size);
		get_file_data(files[x], buff, file_size, padd);

		for(y = 0; y < file_size; y+= 4){
			S = (*(uint32_t*)&buff[y]);
		    switch (ops[0]) {
                case '^': A ^= S; break;
                case '+': A += S; break;
                case '-': A -= S; break;
                case '*': A *= S; break;
                case '/': A /= S; break;
            }
            switch (ops[1]){
                case '^': B ^= C; break;
                case '+': B += C; break;
                case '-': B -= C; break;
                case '*': B *= C; break;
                case '/': B /= C; break;
            }
            switch (ops[2]){
                case '^': C ^= A; break;
                case '+': C += A; break;
                case '-': C -= A; break;
                case '*': C *= A; break;
                case '/': C /= A; break;
            }
            switch (ops[3]){
                case '^': A ^= B; break;
                case '+': A += B; break;
                case '-': A -= B; break;
                case '*': A *= B; break;
                case '/': A /= B; break;
            }
		}
		free(buff);
	}
	*checksum = (uint32_t)(C & 0x00000000FFFFFFFF);
	*version = crev_get_file_version(files[1]);
	S = crev_get_file_information(files[1], result, CREV_MAX_RESULT);

	for(x = 0; x < 4; x++){
		if(files[x] != NULL)
			free(files[x]);
	}

	return S;
}
Example #22
0
uint32_t __stdcall crev_ver3(uint8_t *archive_time, uint8_t *archive_name, uint8_t *seed, uint8_t *ini_file, uint8_t *ini_header, uint32_t *version, uint32_t *checksum, uint8_t *result){
	uint32_t                 x = 0;
	uint32_t                 y = 0;
	uint32_t                 z = 0;
	uint32_t                 lret;
	uint8_t                 *files[5];
	//uint8_t                 *tok;
	uint8_t                 *buff;
	uint8_t                 *buff2;
	uint32_t                 archive_rev = 0;
	uint32_t                 header_size = 0;
	sha1_context             sha;
	lockdown_heep            ldh;
	uint32_t                 pe_file;
	PE_IMAGE_NT_HEADERS     *nt;
	PE_IMAGE_SECTION_HEADER *sections;

	const uint8_t *keys[] = {"Exe", "Util", "Network", "Screen"};
	const uint32_t seeds[] = {
		0xA1F3055A, 0x5657124C, 0x1780AB47, 0x80B3A410, 0xAF2179EA, 
		0x0837B808, 0x6F2516C6, 0xE3178148, 0x0FCF90B6, 0xF2F09516, 
		0x378D8D8C, 0x07F8E083, 0xB0EE9741, 0x7923C9AF, 0xCA11A05E, 
		0xD723C016, 0xFD545590, 0xFB600C2E, 0x684C8785, 0x58BEDE0B
	};
	sha.version = lSHA1;
	sha1_reset(&sha);
	
	if( (archive_name[14] < '0' || archive_name[14] > '1') ||
		(archive_name[15] < '0' || archive_name[15] > '9')){
		return CREV_UNKNOWN_REVISION;
	}

	archive_rev = ((archive_name[14] - '0') * 10) +
				   (archive_name[15] - '0');

	buff = safe_malloc(MAX_PATH);
	read_ini_new(ini_file, ini_header, "Path", "", buff, MAX_PATH);
	files[0] = safe_malloc(MAX_PATH);
	
	combine_paths(buff, "", files[0], MAX_PATH);

	for(x = 1; x < 5; x++){
		read_ini_new(ini_file, ini_header, (uint8_t*)keys[x-1], "\xFF", buff, MAX_PATH);
		if(buff[0] == 0xFF){
			for(y = 0; y < x; y++)
				if(files[y] != NULL) free(files[y]);
			sprintf_s(result, crev_max_result(), "%s\x00", keys[x-1]);
			free(buff);
			return CREV_MISSING_FILENAME;
		}
		files[x] = safe_malloc(MAX_PATH);
		combine_paths(files[0], buff, files[x], MAX_PATH);
	}

	read_ini_new(ini_file, "CRev_Main", "LockdownPath", "", buff, MAX_PATH);

	combine_paths(buff, "", files[0], MAX_PATH);
	sprintf_s(files[0], MAX_PATH, "%s\\Lockdown-IX86-%02d.dll", files[0], archive_rev);
	free(buff);

	lockdown_shuffle_seed(seed);

	buff = safe_malloc(0x40);
	memset(buff, '6', 0x40);

	for(x = 0; x < 0x10; x++)
		buff[x] ^= seed[x];
	sha1_input(&sha, buff, 0x40);
	free(buff);

	for(x = 0; x < 4; x++){
		pe_file = pe_load_library(files[x]);
		if(pe_file == 0){
			sprintf_s(result, CREV_MAX_RESULT, files[x]);
			for(z = 0; z < 5; z++) if(files[z] != NULL) free(files[z]);
			return CREV_MISSING_FILE;
		}
		nt = (PE_IMAGE_NT_HEADERS*)(pe_file + ((PE_IMAGE_DOS_HEADER*)pe_file)->e_lfanew);
		if(nt->OptionalHeader.NumberOfRvaAndSizes <= 0x0D){
			for(z = 0; z < 5; z++) if(files[z] != NULL) free(files[z]);
			pe_unload_library(pe_file);
			return CREV_TOFEW_RVAS;
		}

		header_size = nt->OptionalHeader.SizeOfHeaders;
		if((header_size % nt->OptionalHeader.FileAlignment) != 0)
			header_size += (nt->OptionalHeader.FileAlignment - (header_size % nt->OptionalHeader.FileAlignment));

		sha1_input(&sha, (uint8_t*)pe_file, header_size); //Hash the PE Header

		
		lockdown_heep_create(&ldh);

		lret = lockdown_proc_reloc(pe_file, &ldh);
		if(lret != CREV_SUCCESS){
			sprintf_s(result, CREV_MAX_RESULT, files[x]);
			for(z = 0; z < 5; z++) if(files[z] != NULL) free(files[z]);
			pe_unload_library(pe_file);
			return lret;
		}

		lret = lockdown_proc_import(pe_file, &ldh);
		if(lret != CREV_SUCCESS){
			sprintf_s(result, CREV_MAX_RESULT, files[x]);
			for(z = 0; z < 5; z++) if(files[z] != NULL) free(files[z]);
			pe_unload_library(pe_file);
			return lret;
		}


		lockdown_heep_sort(&ldh);
		/*for(y = 0; y < ldh.cur_len; y += 0x10){
			wwrite_to_file(tto_hex((uint8_t*)(ldh.mem + y), 16, FALSE)); 
			wwrite_to_file("\n");
		}*/

		sections = (PE_IMAGE_SECTION_HEADER *)(pe_file + nt->FileHeader.SizeOfOptionalHeader + ((PE_IMAGE_DOS_HEADER*)pe_file)->e_lfanew + PE_SIZE_OF_NT_SIGNATURE + PE_IMAGE_SIZEOF_FILE_HEADER);

		for(y = 0; y < nt->FileHeader.NumberOfSections; y++){
			lret = lockdown_hash1(&sha, &ldh, (uint32_t)(&sections[y]), pe_file, seeds[archive_rev]);
			if(lret != CREV_SUCCESS){
				sprintf_s(result, CREV_MAX_RESULT, files[x]);
				for(z = 0; z < 5; z++) if(files[z] != NULL) free(files[z]);
				pe_unload_library(pe_file);
				return lret;
			}
		}

		lockdown_heep_cleanup(&ldh);
		pe_unload_library(pe_file);
	}

	//Hash Screen Buffer
	x = get_file_size(files[4]);
	if(x == 0){
		sprintf_s(result, CREV_MAX_RESULT, files[3]);
		return CREV_MISSING_FILE;
	}
	buff = safe_malloc(x);
	get_file_data(files[4], buff, x, 0);
	sha1_input(&sha, buff, x);
	free(buff);

	sha1_input(&sha, "\x01\x00\x00\x00", 4); //Verify Return Address
	sha1_input(&sha, "\x00\x00\x00\x00", 4); //Verify Module Offset
	buff2 = safe_malloc(sha1_hash_size);
	sha1_digest(&sha, buff2);
	//wwrite_to_file(tto_hex(buff2, sha1_hash_size, FALSE)); wwrite_to_file("\n");

	//Second SHA Pass
	buff = safe_malloc(0x40);
	memset(buff, '\\', 0x40);

	for(x = 0; x < 0x10; x++)
		buff[x] ^= seed[x];
	sha1_reset(&sha);
	sha1_input(&sha, buff, 0x40);
	sha1_input(&sha, buff2, sha1_hash_size);
	memset(buff2, 0, sha1_hash_size);
	sha1_digest(&sha, buff2);

	lockdown_shuffle_digest((uint8_t*)(&buff2[4]));

	*version = crev_get_file_version(files[1]);
	*checksum = (*(uint32_t*)&buff2[0]);
	memcpy(result, (uint8_t*)(&buff2[4]), 0x10);
	
	for(x = 0; x < 5; x++) 
		if(files[x] != NULL) free(files[x]);
	return CREV_SUCCESS;
}
Example #23
0
unsigned int fopen(char* filename){
	if(!is_file(filename))
		return 0;

	return (unsigned int) get_file_data(filename);
}
Example #24
0
bool get_image_feature(
	const wchar_t * file_path,
	char *rs_md5)
{
	unsigned short Num = 0;
	CPeFile pe;

	auto st_size = get_file_data(file_path, nullptr);
	if (!st_size) {
		return false;
	}

	auto file_data = new char[st_size];
	if (!get_file_data(file_path, file_data)) {
		return false;
	}

	auto if_openfile_success = pe.Attach(file_path);
	if (if_openfile_success == 0UL ||
		if_openfile_success == 1UL ||
		if_openfile_success == 2UL) {
		return false;
	}
	
	auto p_nt_header = const_cast<PIMAGE_NT_HEADERS32>(pe.GetNtHeader());
	auto p_data_directory = &pe.GetDataDirectory()[IMAGE_DIRECTORY_ENTRY_RESOURCE];
	if (p_data_directory->Size == 0 || p_data_directory->VirtualAddress == 0) {
		return false;
	}
	auto p_reg_directory = reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY>(const_cast<char*>(file_data) + CalcOffset(p_data_directory->VirtualAddress, p_nt_header));
	auto re_size = p_reg_directory->NumberOfIdEntries + p_reg_directory->NumberOfNamedEntries;
	auto p_reg_directory_entry = reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>((long)p_reg_directory + sizeof(IMAGE_RESOURCE_DIRECTORY));

	for (DWORD FirstOrder = 0; FirstOrder < re_size; FirstOrder++) {
		if (p_reg_directory_entry->Name != 0x03) {
			p_reg_directory_entry++;
			continue;
		}

		auto p_reg_directory2 = (PIMAGE_RESOURCE_DIRECTORY)((long)p_reg_directory + p_reg_directory_entry->OffsetToDirectory);
		auto re_size2 = p_reg_directory2->NumberOfIdEntries + p_reg_directory2->NumberOfNamedEntries;
		auto p_reg_directory_entry2 = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((long)p_reg_directory2 + sizeof(IMAGE_RESOURCE_DIRECTORY));
		for (unsigned int second_order = 0; second_order < re_size2; second_order++) {
			if (p_reg_directory_entry2->DataIsDirectory != 1) {
				break;
			}
			//解析第三层 
			auto p_reg_directory3 = (PIMAGE_RESOURCE_DIRECTORY)((long)p_reg_directory + p_reg_directory_entry2->OffsetToDirectory);
			auto p_reg_directory_entry3 = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((long)p_reg_directory3 + sizeof(IMAGE_RESOURCE_DIRECTORY));
			auto reg_data = (PIMAGE_RESOURCE_DATA_ENTRY)((long)p_reg_directory + p_reg_directory_entry3->OffsetToData);
			auto image_data = reinterpret_cast<const char*>(reinterpret_cast<unsigned long>(file_data) + CalcOffset(reg_data->OffsetToData, p_nt_header));
			
			if (reg_data->Size > 0x50000) {
				break;
			}
			string str_md5 = "";
			MD5 md5;                 //定义MD5的类  
			if (!IsBadReadPtr(image_data, reg_data->Size)) {
				md5.update(image_data, reg_data->Size);
				str_md5 = md5.toString();
			}

			if (str_md5 != "" && rs_md5) {
				strcpy(rs_md5, str_md5.c_str());
				return true;
			}

			p_reg_directory_entry2++;
		}
		p_reg_directory_entry++;
	}

	return false;
}
Example #25
0
void* worker_main (void* arg) {
	int thread_id = *((int*)arg);
	free(arg);

	while (1) {
		void* item = queue_consume( &request_queue );
		
		// this happens only if queue_consume_all() was called and no items remain.
		if( item == (void*)-1 ) {
			printf( "Worker exiting.\n" );
			pthread_exit( (void*)NULL );
		}
		
		request_t* req = (request_t*)item;
		char* buf = NULL;
		
		// if cache is enabled then try to get the cached entry.
		int size = config.cache_enabled ? get_cache( req->filename, &buf ) : -1;
		int cache_hit = (size != -1);
		
		// if it wasn't a hit, try to get the data from file.
		if( !cache_hit ) {
			size = get_file_data( req->filename, &buf );
			
			if( size == -1 ) {
				// file does not exist. send result and move on.
				log_message( thread_id, req->req_num, req->fd, cache_hit, req->filename, 404);
				return_error( req->fd, "404 - File not found" );
				
				continue;
			} 
			
			// if cache is enabled then put the value into the cache.
			if( config.cache_enabled ) {
				if( put_cache( req->filename, buf, size ) == -1 ) {
					// error. I think we can keep going?
					fprintf( stderr, "error putting into cache %s\n", req->filename );
					
					// do not escape. this is not a fatal error, so continue sending
					// request to client.
				}
			}
		} 
		
		char* content_type = get_content_type( req->filename );


		// send result and log.
		log_message(thread_id, req->req_num, req->fd, cache_hit, req->filename, size);
		if (return_result( req->fd, content_type, buf, size ) != 0) {
			fprintf(stderr, "Error returning request to client.");
		}

		// only put stuff into prefetch if cache is enabled. otherwise just free the request.
		if( config.cache_enabled ) {
			if( queue_produce( &prefetch_queue, req ) == -1 ) {
				fprintf( stderr, "Error putting request into prefetch queue '%s'\n", req->filename );
			}
		} else {
			// free request created by dispatch.
			free( req->filename );
			free( req );
			
			// free the buffer.
			free( buf );
		}
	}

}