/** * @brief Echo the data for IPI testing * * This function copies the request buffer to response buffer to show the * IPI functionality * * @param req_buf: Virtual address of the request buffer * @param req_buf_len: Request buffer length * @param res_buf: Virtual address of the response buffer * @param res_buf_len: Response buffer length * @param meta_data: Virtual address of the meta data of the encoded data * @param ret_res_buf_len: Return length of the response buffer * * @return SMC return codes: * SMC_SUCCESS: API processed successfully. \n * SMC_*: An implementation-defined error code for any other error. */ int process_otz_echo_ipi_send_cmd(void *req_buf, u32 req_buf_len, void *res_buf, u32 res_buf_len, struct otzc_encode_meta *meta_data, u32 *ret_res_buf_len) { echo_data_t echo_data; char *out_buf; int offset = 0, pos = 0, mapped = 0, type, out_len; if(req_buf_len > 0) { while (offset <= req_buf_len) { if(decode_data(req_buf, meta_data, &type, &offset, &pos, &mapped, (void**)&out_buf, &out_len)) { return SMC_EINVAL_ARG; } else { if(type != OTZ_MEM_REF) return SMC_EINVAL_ARG; sw_memcpy(echo_data.data, out_buf, out_len); echo_data.len = out_len; } break; } } offset = 0, pos = OTZ_MAX_REQ_PARAMS; if (res_buf_len > 0) { while (offset <= res_buf_len) { if(decode_data(res_buf, meta_data, &type, &offset, &pos, &mapped, (void**)&out_buf, &out_len)) { return SMC_EINVAL_ARG; } else { if(type != OTZ_MEM_REF) return SMC_EINVAL_ARG; } sw_memcpy(out_buf, echo_data.data, echo_data.len); if(update_response_len(meta_data, pos, echo_data.len)) return SMC_EINVAL_ARG; break; } *ret_res_buf_len = echo_data.len; } /* sw_printf("SW: echo send cmd %s and len 0x%x strlen 0x%x\n", echo_data.data, echo_data.len, sw_strlen(echo_data.data)); */ return 0; }
/** * Verify that a buffer contains a valid packet. * \param[in] h The packet handler instance data pointer. * \param[in] p A pointer to the packet buffer. * \param[in] received_len The length of data received. * \return < 0 Failure * \return > 0 Number of bytes consumed. */ int32_t PHVerifyPacket(PHInstHandle h, PHPacketHandle p, uint16_t received_len) { // Verify the packet length. // Note: The last two bytes should be the RSSI and AFC. uint16_t len = PHPacketSizeECC(p); if (received_len < (len + 2)) { DEBUG_PRINTF(1, "Packet length error %d %d\n\r", received_len, len + 2); return -1; } // Attempt to correct any errors in the packet. decode_data((unsigned char*)p, len); // Check that there were no unfixed errors. bool rx_error = check_syndrome() != 0; if(rx_error) { DEBUG_PRINTF(1, "Error in packet\n\r"); return -2; } return len + 2; }
// Set senderid, packetcounter and CRC into the partly filled packet, encrypt it using the given AES key number and send it. void send_packet(uint8_t aes_key_nr, uint8_t packet_len) { pkg_header_set_senderid(device_id); inc_packetcounter(); pkg_header_set_packetcounter(packetcounter); // set CRC32 pkg_header_set_crc32(crc32(bufx + 4, packet_len - 4)); // load AES key (0 is first AES key) if (aes_key_nr >= aes_key_count) { aes_key_nr = aes_key_count - 1; } e2p_basestation_get_aeskey(aes_key_nr, aes_key); // show info decode_data(packet_len); // encrypt and send __PACKETSIZEBYTES = packet_len; rfm12_send_bufx(); }
int show_status(ADDRESS_BOOK config) { FILE *fp; struct address_data data; int record, record_active, record_hide; char buf[1024]; fp = fopen(config.filename, "r"); if(!fp) { fprintf(stderr, "Error: file open [%s]\n", config.filename); return -1; } printf("=====================================\n"); for(record = 0, record_active = 0, record_hide = 0; ;) { if(fgets(buf, sizeof(buf), fp) == 0) break; record ++; data = decode_data(buf); if(data.status == (0x01 << ACTIVE)) { record_active++; } else if(data.status == (0x01 << HIDE)) { record_hide++; } } printf("Number of record: %d\n", record); printf("Number of active record: %d\n", record_active); printf("=====================================\n"); fclose(fp); return 0; }
int load_file(ADDRESS_BOOK *config) { FILE *fp; char buf[1024]; char *filename = config->filename; int width_name, width_address; struct address_data data; fp = fopen(filename, "r"); if(!fp) { fprintf(stderr, "Error: file open [%s]\n", filename); return -1; } while(1) { if(fgets(buf, sizeof(buf), fp) == 0) break; config->last_id = atoi(buf); } fseek(fp, 0, SEEK_SET); for(width_name = 0, width_address = 0; ;) { if(fgets(buf, sizeof(buf), fp) == 0) break; data = decode_data(buf); if(width_name < strlen(data.name)) width_name = strlen(data.name); if(width_address < strlen(data.address)) width_address = strlen(data.address); } config->width_name = width_name; config->width_address = width_address; fclose(fp); return 0; }
void decode_file(FILE *fpi, FILE *fpo) { size_t n, x; unsigned long len; unsigned char cont[CONTSIZE], data[DATASIZE]; struct stash_hdr shdr = {0}; // Skip restricted area (void)fseek(fpi, STARTBYTE, SEEK_SET); // Get header n = fread(data, 1, sizeof(struct stash_hdr)<<3, fpi); decode_data((unsigned char *)&shdr, sizeof(struct stash_hdr), data, (int)n, 0); // Decode data len = shdr.len; while(len > 0) { if(len >= DATASIZE) x = DATASIZE; else x = len; n = fread(cont, 1, x<<3, fpi); decode_data(data, (int)n>>3, cont, (int)n, 1); fwrite(data, 1, (int)x, fpo); len -= (unsigned long)x; } return; }
void ICACHE_FLASH_ATTR pando_subdevice_recv(uint8_t * buffer, uint16_t length) { if(NULL == buffer) { return; } PRINTF("subdevive receive a package: \n"); show_package(buffer, length); struct sub_device_buffer *device_buffer = (struct sub_device_buffer *)pd_malloc(sizeof(struct sub_device_buffer)); device_buffer->buffer_length = length; device_buffer->buffer = (uint8 *)pd_malloc(length); pd_memcpy(device_buffer->buffer, buffer, length); uint16 payload_type = get_sub_device_payloadtype(device_buffer); switch (payload_type) { case PAYLOAD_TYPE_DATA: decode_data(device_buffer); break; case PAYLOAD_TYPE_COMMAND: decode_command(device_buffer); break; default: PRINTF("unsuported paload type : %d", payload_type); break; } delete_device_package(device_buffer); }
void Simulation::decodedReceiveData(int length, const uint8 *data, uint32 /*src*/) { DBG("decodedReceiveData(%i, xxxx)\n", length); if (m_shutdown) { return; } decode_data(data, length, 0, 0); }
int main (int argc, char *argv[]) { int erasures[16]; int nerasures = 0; /* Initialization the ECC library */ initialize_ecc (); /* ************** */ /* Encode data into codeword, adding NPAR parity bytes */ encode_data(msg, sizeof(msg), codeword); printf("Encoded data is: \"%s\"\n", codeword); printf("Encoded data length: \"%d\"\n", sizeof(codeword)); printf("msg length: \"%d\"\n", sizeof(msg)); int i; for (i = 0; (i < sizeof(msg)); i++) { printf("%02x", msg[i]); } printf("\n"); for (i = 0; (i < sizeof(codeword)); i++) { printf("%02x", codeword[i]); } printf("\n"); #define ML (sizeof (msg) + NPAR) /* We need to indicate the position of the erasures. Eraseure positions are indexed (1 based) from the end of the message... */ erasures[nerasures++] = ML-17; erasures[nerasures++] = ML-19; /* Now decode -- encoded codeword size must be passed */ decode_data(codeword, ML); /* check if syndrome is all zeros */ if (check_syndrome () != 0) { correct_errors_erasures (codeword, ML, nerasures, erasures); printf("Corrected codeword: \"%s\"\n", codeword); } exit(0); }
void DecoderStack::decode_proc() { optional<int64_t> sample_count; srd_session *session; srd_decoder_inst *prev_di = NULL; assert(_snapshot); // Create the session srd_session_new(&session); assert(session); // Create the decoders const unsigned int unit_size = _snapshot->unit_size(); for (const shared_ptr<decode::Decoder> &dec : _stack) { srd_decoder_inst *const di = dec->create_decoder_inst(session, unit_size); if (!di) { _error_message = tr("Failed to create decoder instance"); srd_session_destroy(session); return; } if (prev_di) srd_inst_stack (session, prev_di, di); prev_di = di; } // Get the intial sample count { unique_lock<mutex> input_lock(_input_mutex); sample_count = _sample_count = _snapshot->get_sample_count(); } // Start the session srd_session_metadata_set(session, SRD_CONF_SAMPLERATE, g_variant_new_uint64((uint64_t)_samplerate)); srd_pd_output_callback_add(session, SRD_OUTPUT_ANN, DecoderStack::annotation_callback, this); srd_session_start(session); do { decode_data(*sample_count, unit_size, session); } while(_error_message.isEmpty() && (sample_count = wait_for_data())); // Destroy the session srd_session_destroy(session); }
int main(int argc, char *argv[]) { mqd_t q_handler_encoded_data, q_handler_decoded_data; mode_t mode_read_only = O_RDONLY; mode_t mode_write_only = O_WRONLY; /* Open message queues */ open_message_queue(MQ_ENCODED_DATA, mode_read_only, &q_handler_encoded_data); open_message_queue(MQ_DECODED_DATA, mode_write_only, &q_handler_decoded_data); /* Task management */ decode_data(q_handler_encoded_data, q_handler_decoded_data); return EXIT_SUCCESS; }
int AndCodec_EasyDecoderAdd(int dec, unsigned char* decdata, int decdata_size, unsigned char* opaque, int opaque_len) { and_log_writeline_simple(0, LOG_DEBUG, "AndCodec_EasyDecoderAdd()"); if(!dec) { and_log_writeline_simple(0, LOG_ERROR, "decoder handle is null"); return -1; } if(!decdata) { and_log_writeline_simple(0, LOG_ERROR, "decode data is null"); return -1; } easy_decoder_handle* handle = (easy_decoder_handle *)dec; return decode_data(handle, decdata, decdata_size, opaque, opaque_len); }
void continuous_test(double ebn0) { uint8_t data[256] = {0}; uint8_t encoded[650] = {0}; uint8_t bits[5200] = {0}; uint8_t dec_data[256] = {0}; int8_t error[2] = {0}; FILE *fp; uint16_t i; // Es/No in dB - Energy per symbol (symbol, like channel bit) double esn0 = ebn0 + 10*log10(1. / 2.); // Compute noise voltage. The 0.5 factor accounts for BPSK seeing // only half the noise power, and the sqrt() converts power to // voltage. double gain = 1./sqrt(0.5/pow(10.,esn0/10.)); gettimeofday(&start, NULL); while (run) { generate_random_data(&data); #if (DEBUG >= 1) fp = fopen("data", "wb"); fwrite(data, 256, 1, fp); fclose(fp); #endif encode_data(&data, &encoded); // AWGN channel simulation for (i=0; i<5200; ++i) { bits[i] = addnoise(encoded[i>>3] & (1 << (7 - (i & 7))), gain, 32.0); } decode_data(&bits, &dec_data, &error); #if (DEBUG >= 1) fp = fopen("dec_data", "wb"); fwrite(dec_data, 256, 1, fp); fclose(fp); #endif stat_refresh(&error, is_equal(&data, &dec_data)); } }
TEST_F(EncodeDecode, Recover) { unsigned char p[10] = {'a', 'b', 'c', 'd', 'e', 'f'}; encode_data(p, 6, p); unsigned char p2[10]; for (int i = 0; i < 10; i++) p2[i] = p[i]; p2[4] = 30; // verify it flags the error decode_data(p2, 6 + RS_ECC_NPARITY); EXPECT_EQ(1, check_syndrome()); // verify it is corrected EXPECT_EQ(1, correct_errors_erasures(p2, 10, 0, 0)); for (int i = 0; i < 6; i++) EXPECT_EQ(p[i], p2[i]); };
void send_packet(uint8_t aes_key_nr, uint8_t data_len) { // set device ID (base station has ID 0 by definition) bufx[0] = 0; // update packet counter packetcounter++; if (packetcounter % PACKET_COUNTER_WRITE_CYCLE == 0) { eeprom_write_dword((uint32_t*)0, packetcounter); } setBuf32(1, packetcounter); // set CRC32 uint32_t crc = crc32(bufx, data_len + 6); setBuf32(data_len + 6, crc); // load AES key (0 is first AES key) if (aes_key_nr >= AES_KEY_EEPROM_COUNT) { aes_key_nr = AES_KEY_EEPROM_COUNT - 1; } eeprom_read_block (aes_key, (uint8_t *)(EEPROM_POS_AES_KEY + aes_key_nr * 32), 32); // show info decode_data(data_len + 6); UART_PUTF(" AES key: %u\r\n", aes_key_nr); UART_PUTF(" CRC32: %02lx\r\n", crc); UART_PUTS(" Unencrypted: "); printbytearray(bufx, data_len + 10); // encrypt and send uint8_t aes_byte_count = rfm12_sendbuf(data_len + 10); UART_PUTS("Send encrypted: "); printbytearray(bufx, aes_byte_count); UART_PUTS("\r\n"); }
int show_data(ADDRESS_BOOK config) { FILE *fp; struct address_data data; char buf[1024]; char format_str[1024]; char *filename = config.filename; int i; int str_count; fp = fopen(filename, "r"); if(!fp) { fprintf(stderr, "Error: file open [%s]\n", filename); return -1; } sprintf(format_str, "| %%%ds | %%%ds | %%11s |\n", config.width_name, config.width_address); str_count = sprintf(buf, format_str, "Name", "Address", "Phone") - 1; // ignore new line charactor for(i = str_count; i > 0; i--) printf("="); printf("\n"); printf("%s", buf); for(i = str_count; i > 0; i--) printf("="); printf("\n"); sprintf(format_str, "| %%%ds | %%%ds | ", config.width_name, config.width_address); while(1) { if(fgets(buf, sizeof(buf), fp) == 0) break; data = decode_data(buf); if(data.no == 0) continue; if(data.status == (0x01 << HIDE)) continue; printf(format_str, data.name, data.address); for(i = 0; data.phone[i] != END_OF_PHONE_NUMBER; i++) { printf("%d", data.phone[i]); } printf(" |\n"); } for(i = str_count; i > 0; i--) printf("="); printf("\n"); fclose(fp); return 0; }
Buffer * PCMDecoder::decode(std::ifstream &in) const { RAII_PCMDecoderData decode_data(in); Buffer *buffer = nullptr; try { RIFFHeaderChunk header_chunk; in.readsome((char *)&header_chunk, sizeof(RIFFHeaderChunk)); if (strncmp(header_chunk.id, "RIFF", 4) != 0 && strncpy(header_chunk.format, "WAVE", 4) != 0) { Error::raise(Error::Status::PCMError, "Bad file format."); } debug_riff_header_chunk(header_chunk); WaveFormatChunk format_chunk; in.readsome((char *)&format_chunk, sizeof(WaveFormatChunk)); if (strncmp(format_chunk.id, "fmt ", 4) != 0) { Error::raise(Error::Status::PCMError, "Bad file format."); } debug_wave_format_chunk(format_chunk); WaveDataChunk data_chunk; in.readsome((char *)&data_chunk, sizeof(WaveDataChunk)); if (strncmp(data_chunk.id, "data", 4) != 0) { Error::raise(Error::Status::PCMError, "Bad file format."); } debug_wave_data_chunk(data_chunk); Format format(format_chunk.channelCount, format_chunk.sampleRate, format_chunk.bitPerSample); decode_data.samples = (char *) malloc(data_chunk.size); in.read(decode_data.samples, data_chunk.size); buffer = new Buffer(format, data_chunk.size, decode_data.samples); decode_data.samples = nullptr; } catch (std::ifstream::failure ioerr) { Error::raise(Error::Status::IOError, ioerr.what()); } return buffer; }
bool ArchiveDataClient::decode_channel(xmlrpc_value *channel, size_t n, value_callback callback, void *callback_arg) { char *name; xmlrpc_value *meta, *data; xmlrpc_int32 type, count; xmlrpc_parse_value(&env, channel, "{s:s,s:V,s:i,s:i,s:A,*}", "name", &name, "meta", &meta, "type", &type, "count", &count, "values", &data); if (log_fault()) return false; CtrlInfo ctrlinfo; if (!decode_meta(meta, ctrlinfo)) return false; return decode_data(name, type, count, data, ctrlinfo, n, callback, callback_arg); }
uint8_t NUNCHUCK::retreive_data(){ Wire.requestFrom(NUNADDRESS, 6); uint8_t index = 0; while(Wire.available()){ nunDataArr[index] = decode_data(Wire.read()); index++; } request_data(); if(nunDataArr[5] != NULL){ return 1; } else { return 0; } }
int decode_trau_frame(struct decoded_trau_frame *fr, const uint8_t *trau_bits) { uint8_t cbits5 = get_bits(trau_bits, 17, 5); switch (cbits5) { case TRAU_FT_FR_UP: case TRAU_FT_FR_DOWN: case TRAU_FT_IDLE_UP: case TRAU_FT_IDLE_DOWN: case TRAU_FT_EFR: decode_fr(fr, trau_bits); break; case TRAU_FT_AMR: decode_amr(fr, trau_bits); break; case TRAU_FT_DATA_UP: case TRAU_FT_DATA_DOWN: decode_data(fr, trau_bits); break; case TRAU_FT_OM_UP: case TRAU_FT_OM_DOWN: case TRAU_FT_D145_SYNC: case TRAU_FT_EDATA: LOGP(DLMUX, LOGL_NOTICE, "can't decode unimplemented TRAU " "Frame Type 0x%02x\n", cbits5); return -1; break; default: LOGP(DLMUX, LOGL_NOTICE, "can't decode unknown TRAU " "Frame Type 0x%02x\n", cbits5); return -1; break; } return 0; }
//concatenated decoding void inner_decoding(decoded_blocks *db,unsigned char * c_in_codeword, unsigned long * indices){ int p; //for(p=0;p<v;p++) { // printf("random index #%d: %lu\n",p,indices[p]); //} unsigned char c_in_message[v*k2],temp[n2],c_out_codeword[n1],c_out_message[v*k1]; int c_index=0,m_index=0,i,j,m,index=0; int erasure[1]; // cin decoding printf("concatenated Cin decoding...\n"); for(j=0;j<w*32/n2;j++){ for(i=0;i<n2;i++){ temp[i]=c_in_codeword[c_index++]; } decode_data(temp, n2); if (check_syndrome () != 0) { correct_errors_erasures(temp,n2,0,erasure); } for(i=0;i<k2;i++){ c_in_message[m_index++]=temp[k2]; } } //cout decoding: get the file and parity part printf("concatenated Cout decoding...\n"); c_index=0; for(i=0;i<v;i++){ index=0; //create codeword //copy message part for(j=0;j<k1;j++){ c_out_codeword[index++]=c_in_message[j]; } //copy parity part codeword p = (m_index/2) + (i*d1); for(j=0;j<d1;j++){ c_out_codeword[index++]=c_in_message[j+p]; } decode_data(c_out_codeword, n1); if (check_syndrome () != 0) { correct_errors_erasures(c_out_codeword,n1,0,erasure); } for(j=0;j<k1;j++){ c_out_message[c_index++]=c_out_codeword[j]; } } //c_out_message contains v decoded blocks //divide decoded message into v blocks from f1 to fv. printf("updating Di...\n"); for(i=0;i<v;i++){ printf("indices[%d]=%lu\n",i,indices[i]); //divide codeword into 32 byte blocks int fi = indices[i]; char block[32]; for(j=0;j<32;j++){ block[j]=c_out_message[(i*32)+j]; } //check if similar codeword was already decoded and present in Di //if yes, just increase the frequency int notfound=1; for(j=0;j<alpha;j++){ int flag=1; fflush(stdout); if(db[fi].frequency[j]==0) break; for(m=0;m<32;m++){ if(db[fi].file_blocks[j][m]!=block[m]){ flag=0; break; } } if(flag){ //int freq = db[fi].frequency[j]; db[fi].frequency[j]++; notfound=0; } } //if not found, add it in di if(notfound){ for(m=0;m<32;m++){ db[fi].file_blocks[j][m] = block[m]; } db[fi].frequency[j] = 1; } } }
int edit_data(ADDRESS_BOOK *config) { int type; int match_flag = 0; int phone_flag = 0; int count; int index; int i, j, k; char buf[1024]; char format_str[1024]; char input_flag = 0; FILE *fp; char *filename = config->filename; struct address_data search, data; struct address_data list[1024]; int list_index[1024]; enum { ID, NAME, ADDRESS, PHONE, }; do { puts( "Please choose entry\n" "select search type\n" "[ID, Name, Address, Phone]"); fgets(buf, sizeof(buf), stdin); buf[strlen(buf) - 1] = '\0'; if(!strcmp(buf, "id") | !strcmp(buf, "Id") | !strcmp(buf, "ID")) { type = ID; input_flag = 1; } else if(!strcmp(buf, "name") | !strcmp(buf, "Name") | !strcmp(buf, "NAME")) { type = NAME; input_flag = 1; } else if(!strcmp(buf, "address") | !strcmp(buf, "Address") | !strcmp(buf, "ADDRESS")) { type = ADDRESS; input_flag = 1; } else if(!strcmp(buf, "phone") | !strcmp(buf, "Phone") | !strcmp(buf, "PHONE")) { type = PHONE; input_flag = 1; } } while(input_flag == 0); switch(type) { case ID: do { puts("Please enter id for edit"); printf("> "); fgets(buf, sizeof(buf), stdin); search.no = atoi(buf); } while(search.no == 0); break; case NAME: puts("Please enter name for edit"); printf("> "); fgets(buf, sizeof(buf), stdin); buf[strlen(buf) - 1] = '\0'; strncpy(search.name, buf, sizeof(search.name)); break; case ADDRESS: puts("Please enter address for edit"); printf("> "); fgets(buf, sizeof(buf), stdin); buf[strlen(buf) - 1] = '\0'; strncpy(search.address, buf, sizeof(search.address)); break; case PHONE: puts("Please enter phone number for edit"); printf("> "); fgets(buf, sizeof(buf), stdin); for(i = 0; buf[i] != '\n'; i++) { search.phone[i] = buf[i] - '0'; } search.phone[i] = END_OF_PHONE_NUMBER; break; } fp = fopen(filename, "r"); if(!fp) { fprintf(stderr, "Error: file open [%s]\n", filename); return -1; } for(count = 0, index = 0;;) { match_flag = 0; if(fgets(buf, sizeof(buf), fp) == 0) break; data = decode_data(buf); if(data.no == 0) continue; list[count] = data; list_index[count] = 0; if(data.status == (0x01 << HIDE)) { count++; continue; } switch(type) { case ID: if(search.no == data.no) match_flag = 1; break; case NAME: if(!strcmp(search.name, data.name)) match_flag = 1; else { for(i = 0; data.name[i] != '\0'; i++) { buf[i] = tolower(data.name[i]); } buf[i] = '\0'; if(!strcmp(search.name, buf)) match_flag = 1; } break; case ADDRESS: if(!strcmp(search.address, data.address)) match_flag = 1; break; case PHONE: for(i = 0; search.phone[i] != END_OF_PHONE_NUMBER && data.phone[i] != END_OF_PHONE_NUMBER; i++) { phone_flag = 0; if(search.phone[i] != data.phone[i]) break; phone_flag = 1; } if(phone_flag) match_flag = 1; break; } if(match_flag != 0) { list_index[count] = 1; index++; } count++; } if(index == 0) { puts("Not found!"); } else if(index == 1) { for(i = 0; i < count; i++) { if(list_index[i] == 1) { list[i].status = (0x01 << HIDE); break; } } } else if(index > 1) { printf("Find some entries!\nChoose entry\n"); for(i = 0, j = 0; i < count; i++) { if(list_index[i] == 1) { sprintf(format_str, "| %%2d | %%%ds | %%%ds | ", config->width_name, config->width_address); printf(format_str, j + 1, list[i].name, list[i].address); for(k = 0; list[i].phone[k] != END_OF_PHONE_NUMBER; k++) { printf("%d", list[i].phone[k]); } printf(" |\n"); j++; } } fgets(buf, sizeof(buf), stdin); for(i = 0, j = 0; i < count; i++) { if(list_index[i] == 1) { if((j - 1) == atoi(buf)) { list[i].status = (0x01 << HIDE); break; } j++; } } } fclose(fp); fp = fopen(filename, "w"); if(!fp) { fprintf(stderr, "Error: file open [%s]\n", filename); return -1; } for(i = 0; i < count; i++) { fprintf(fp, "%d,%s,%s,", list[i].no, list[i].name, list[i].address); for(k = 0; list[i].phone[k] != END_OF_PHONE_NUMBER; k++) { fprintf(fp, "%d", list[i].phone[k]); } fprintf(fp, ",%d\n", list[i].status); } fclose(fp); input_data(config, &data); append_data_to_file(*config, data); return 0; }
void inner_GMD(decoded_blocks *db,unsigned char * c_in_codeword, unsigned long * indices, FILE * fp){ unsigned char c_in_message[n1*k2],temp[n2],c_out_codeword[n1],c_out_message[v*32]; int c_index=0,m_index=0,i,j,m,index=0; int erasure_index[n1]; // cin decoding printf("concatenated Cin decoding...\n"); for(j=0;j<n1;j++){ for(i=0;i<n2;i++){ temp[i]=c_in_codeword[c_index++]; } unsigned char cpytemp[n2]; memcpy(cpytemp,temp,n2); decode_data(temp, n2); if (check_syndrome () != 0) { int erasure[1]; correct_errors_erasures(temp,n2,0,erasure); } int delta_dist = 0; for(i=0;i<n2;i++){ if(temp[i]!=cpytemp[i]) delta_dist++; } double prob; if(delta_dist<d2/2) prob = 2*(double)delta_dist/d2; else prob = 1.0; srand(time(NULL)); double random_num = (double)rand() / (double)RAND_MAX; for(i=0;i<k2;i++){ if (random_num<prob) c_in_message[m_index++]=0; else c_in_message[m_index++]=temp[i]; } if (random_num<prob) erasure_index[n1] = 1; else erasure_index[n1] = 0; } //printf("display c_in_message\n"); //displayCharArray(c_in_message,sizeof(c_in_message)); printf("concatenated Cout decoding...\n"); c_index=0; for(i=0;i<v;i++){ int erasure[n1]; int num_erasure = 0; index=0; //create codeword //copy message part for(j=0;j<k1;j++){ c_out_codeword[index++]=c_in_message[i*k1+j]; } int p; //copy parity part codeword p = v*32 + (i*d1); for(j=0;j<d1;j++){ c_out_codeword[index++]=c_in_message[j+p]; } //printf("display c_out_codeword for %d\n",i); //displayCharArray(c_out_codeword,sizeof(c_out_codeword)); if(erasure_index[v]==1) { int ki; for(ki=0;ki<k2;ki++) { erasure[num_erasure] = ki; num_erasure++; } } if(erasure_index[v]==1) { int di; for(di=0;di<d2;di++) { erasure[num_erasure] = k2+di; num_erasure++; } } decode_data(c_out_codeword, n1); if (check_syndrome () != 0) { correct_errors_erasures(c_out_codeword,n1,num_erasure,erasure); } for(j=0;j<k1;j++){ c_out_message[c_index++]=c_out_codeword[j]; } } //printf("updating Di...\n"); for(i=0;i<v;i++){ //printf("indices[%d]=%lu\n",i,indices[i]); //divide codeword into 32 byte blocks int fi = indices[i]; unsigned char block[32]; for(j=0;j<32;j++){ block[j]=c_out_message[(i*32)+j]; } //check if similar codeword was already decoded and present in Di //if yes, just increase the frequency int notfound=1; for(j=0;j<alpha;j++){ int flag=1; if(db[fi].frequency[j]==0) break; for(m=0;m<32;m++){ if(db[fi].file_blocks[j][m]!=block[m]){ flag=0; break; } } if(flag){ //int freq = db[fi].frequency[j]; db[fi].frequency[j]++; notfound=0; } } //if not found, add it in di if(notfound){ for(m=0;m<32;m++){ db[fi].file_blocks[j][m] = block[m]; } db[fi].frequency[j] = 1; } /* printf("display db %d:\n",fi); displayCharArray(db[fi].file_blocks[j],32); fseek(fp,fi*32,SEEK_SET); unsigned char buffer[32]; fread(buffer, 32, 1, fp); printf("real content in the file block %d:\n",fi); displayCharArray(buffer,32); */ } }
int search(ADDRESS_BOOK config) { int type; int match_flag = 0; int phone_flag = 0; int count; int i; int first_flag = 1; char buf[1024]; char format_str[1024]; char input_flag = 0; FILE *fp; char *filename = config.filename; struct address_data search, data; enum { ID, NAME, ADDRESS, PHONE, }; do { puts( "select search type\n" "[ID, Name, Address, Phone]"); fgets(buf, sizeof(buf), stdin); buf[strlen(buf) - 1] = '\0'; if(!strcmp(buf, "id") | !strcmp(buf, "Id") | !strcmp(buf, "ID")) { type = ID; input_flag = 1; } else if(!strcmp(buf, "name") | !strcmp(buf, "Name") | !strcmp(buf, "NAME")) { type = NAME; input_flag = 1; } else if(!strcmp(buf, "address") | !strcmp(buf, "Address") | !strcmp(buf, "ADDRESS")) { type = ADDRESS; input_flag = 1; } else if(!strcmp(buf, "phone") | !strcmp(buf, "Phone") | !strcmp(buf, "PHONE")) { type = PHONE; input_flag = 1; } } while(input_flag == 0); switch(type) { case ID: do { puts("Please enter id for search"); printf("> "); fgets(buf, sizeof(buf), stdin); search.no = atoi(buf); } while(search.no == 0); break; case NAME: puts("Please enter name for search"); printf("> "); fgets(buf, sizeof(buf), stdin); buf[strlen(buf) - 1] = '\0'; strncpy(search.name, buf, sizeof(search.name)); break; case ADDRESS: puts("Please enter address for search"); printf("> "); fgets(buf, sizeof(buf), stdin); buf[strlen(buf) - 1] = '\0'; strncpy(search.address, buf, sizeof(search.address)); break; case PHONE: puts("Please enter phone number for search"); printf("> "); fgets(buf, sizeof(buf), stdin); for(i = 0; buf[i] != '\n'; i++) { search.phone[i] = buf[i] - '0'; } search.phone[i] = END_OF_PHONE_NUMBER; break; } fp = fopen(filename, "r"); if(!fp) { fprintf(stderr, "Error: file open [%s]\n", filename); return -1; } puts("========================="); for(count = 0;;) { match_flag = 0; if(fgets(buf, sizeof(buf), fp) == 0) break; data = decode_data(buf); if(data.no == 0) continue; if(data.status == (0x01 << HIDE)) continue; switch(type) { case ID: if(search.no == data.no) match_flag = 1; break; case NAME: if(!strcmp(search.name, data.name)) match_flag = 1; else { for(i = 0; data.name[i] != '\0'; i++) { buf[i] = tolower(data.name[i]); } buf[i] = '\0'; if(!strcmp(search.name, buf)) match_flag = 1; } break; case ADDRESS: if(!strcmp(search.address, data.address)) match_flag = 1; break; case PHONE: for(i = 0; search.phone[i] != END_OF_PHONE_NUMBER && data.phone[i] != END_OF_PHONE_NUMBER; i++) { phone_flag = 0; if(search.phone[i] != data.phone[i]) break; phone_flag = 1; } if(phone_flag) match_flag = 1; break; } if(match_flag != 0) { count++; if(first_flag) { sprintf(format_str, "| %%%ds | %%%ds | %%11s |\n", config.width_name, config.width_address); printf(format_str, "Name", "Address", "Phone number"); first_flag = 0; } sprintf(format_str, "| %%%ds | %%%ds | ", config.width_name, config.width_address); printf(format_str, data.name, data.address); for(i = 0; data.phone[i] != END_OF_PHONE_NUMBER; i++) { printf("%d", data.phone[i]); } printf(" |\n"); } } if(count == 0) { puts("Not found!"); } puts("========================="); fclose(fp); return 0; }
int main(int argc, char** argv) { int rc = 0; struct pando_buffer *bin_buf; uint16_t payload_type = 0; MQTTMessage msg; unsigned char buf[500]; unsigned char readbuf[500]; char payload_type_c[] = {'c', 'e', 'd'}; bin_buf = construct_data_package_to_server(&payload_type); decode_data(bin_buf, PAYLOAD_TYPE_DATA); /* command test, event is same as command except the type */ bin_buf = constuct_event_package_to_server(&payload_type); decode_command(bin_buf, PAYLOAD_TYPE_COMMAND); return 0; if (argc < 2) usage(); char* topic = argv[1]; getopts(argc, argv); if (strchr(topic, '#') || strchr(topic, '+')) opts.showtopics = 1; if (opts.showtopics) printf("topic is %s\n", topic); Network n; Client c; signal(SIGINT, cfinish); signal(SIGTERM, cfinish); NewNetwork(&n); ConnectNetwork(&n, opts.host, opts.port); MQTTClient(&c, &n, 1000, buf, 100, readbuf, 100); MQTTPacket_connectData data = MQTTPacket_connectData_initializer; data.willFlag = 0; data.MQTTVersion = 3; data.clientID.cstring = opts.clientid; data.username.cstring = opts.username; data.password.cstring = opts.password; data.keepAliveInterval = 10; data.cleansession = 1; printf("Connecting to %s %d\n", opts.host, opts.port); rc = MQTTConnect(&c, &data); printf("Connected %d\n", rc); printf("Subscribing to %s\n", topic); rc = MQTTSubscribe(&c, topic, opts.qos, messageArrived); printf("Subscribed %d\n", rc); while (!toStop) { MQTTYield(&c, 1000); if (toSend) { if (strstr(topic, "/d")) { /* data test */ bin_buf = construct_data_package_to_server(&payload_type); //decode_data(bin_buf, PAYLOAD_TYPE_DATA); } if (strstr(topic, "/e")) { /* command test */ bin_buf = constuct_event_package_to_server(&payload_type); //decode_command(bin_buf, PAYLOAD_TYPE_COMMAND); } msg.qos = opts.qos; msg.retained = 0; msg.dup = 0; msg.payload = bin_buf->buffer + bin_buf->offset; msg.payloadlen = bin_buf->buff_len - bin_buf->offset; /* before publish a message, you need to generate a topic with payload_type max device id is 8 bytes, hex to char need 8*2 bytes, '/' need 1 byte, type need 1 byte */ char publish_topic[8*2 + 1 + 1]; memset(publish_topic, 0, sizeof(publish_topic)); sprintf(publish_topic, "%s/%c", opts.clientid, payload_type_c[payload_type - 1]); printf(publish_topic); rc = MQTTPublish(&c, publish_topic, &msg); toSend = 0; pd_free(bin_buf); printf("published rc %d, len %d\n", rc, (int)msg.payloadlen); } } printf("Stopping\n"); MQTTDisconnect(&c); n.disconnect(&n); return 0; }
int main(void) { uint8_t aes_key_nr; uint8_t loop = 0; uint8_t loop2 = 0; // delay 1s to avoid further communication with uart or RFM12 when my programmer resets the MC after 500ms... _delay_ms(1000); util_init(); check_eeprom_compatibility(DEVICETYPE_BASESTATION); request_queue_init(); // read packetcounter, increase by cycle and write back packetcounter = e2p_generic_get_packetcounter() + PACKET_COUNTER_WRITE_CYCLE; e2p_generic_set_packetcounter(packetcounter); // read device specific config aes_key_count = e2p_basestation_get_aeskeycount(); device_id = e2p_generic_get_deviceid(); uart_init(); UART_PUTS("\r\n"); UART_PUTF4("smarthomatic Base Station v%u.%u.%u (%08lx)\r\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_HASH); UART_PUTS("(c) 2012..2014 Uwe Freese, www.smarthomatic.org\r\n"); UART_PUTF("Device ID: %u\r\n", device_id); UART_PUTF("Packet counter: %lu\r\n", packetcounter); UART_PUTF("AES key count: %u\r\n", aes_key_count); UART_PUTS("Waiting for incoming data. Press h for help.\r\n\r\n"); led_blink(500, 500, 3); rfm12_init(); sei(); // ENCODE TEST (Move to unit test some day...) /* uint8_t testlen = 32; uint8_t aes_key_num = 0; memset(&bufx[0], 0, sizeof(bufx)); bufx[0] = 0xff; bufx[1] = 0xb0; bufx[2] = 0xa0; bufx[3] = 0x3f; bufx[4] = 0x01; bufx[5] = 0x70; bufx[6] = 0x00; bufx[7] = 0x0c; bufx[8] = 0xa8; bufx[9] = 0x00; bufx[10] = 0x20; bufx[20] = 0x20; eeprom_read_block (aes_key, (uint8_t *)(EEPROM_AESKEYS_BYTE + aes_key_num * 32), 32); UART_PUTS("Using AES key "); print_bytearray((uint8_t *)aes_key, 32); UART_PUTS("Before encryption: "); print_bytearray(bufx, testlen); uint8_t aes_byte_count = aes256_encrypt_cbc(bufx, testlen); UART_PUTF("byte count = %u\r\n", aes_byte_count); UART_PUTS("After encryption: "); print_bytearray(bufx, aes_byte_count); aes256_decrypt_cbc(bufx, aes_byte_count); UART_PUTS("After decryption: "); print_bytearray(bufx, testlen); while(1); */ while (42) { if (rfm12_rx_status() == STATUS_COMPLETE) { uint8_t len = rfm12_rx_len(); if ((len == 0) || (len % 16 != 0)) { UART_PUTF("Received garbage (%u bytes not multiple of 16): ", len); print_bytearray(bufx, len); } else // try to decrypt with all keys stored in EEPROM { bool crcok = false; for (aes_key_nr = 0; aes_key_nr < aes_key_count ; aes_key_nr++) { memcpy(bufx, rfm12_rx_buffer(), len); /*if (aes_key_nr == 0) { UART_PUTS("Before decryption: "); print_bytearray(bufx, len); }*/ e2p_basestation_get_aeskey(aes_key_nr, aes_key); //UART_PUTS("Trying AES key 2 "); //print_bytearray((uint8_t *)aes_key, 32); aes256_decrypt_cbc(bufx, len); //UART_PUTS("Decrypted bytes: "); //print_bytearray(bufx, len); crcok = pkg_header_check_crc32(len); if (crcok) { //UART_PUTS("CRC correct, AES key found!\r\n"); UART_PUTF("Received (AES key %u): ", aes_key_nr); print_bytearray(bufx, len); decode_data(len); break; } } if (!crcok) { UART_PUTS("Received garbage (CRC wrong after decryption): "); memcpy(bufx, rfm12_rx_buffer(), len); print_bytearray(bufx, len); } UART_PUTS("\r\n"); } //uart_hexdump((char *)bufcontents, rfm12_rx_len()); //UART_PUTS("\r\n"); // tell the implementation that the buffer can be reused for the next data. rfm12_rx_clear(); } // send data, if waiting in send buffer if (send_data_avail) { uint8_t i; // set AES key nr aes_key_nr = hex_to_uint8((uint8_t *)cmdbuf, 1); //UART_PUTF("AES KEY = %u\r\n", aes_key_nr); // init packet buffer memset(&bufx[0], 0, sizeof(bufx)); // set message type uint8_t message_type = hex_to_uint8((uint8_t *)cmdbuf, 3); pkg_header_set_messagetype(message_type); pkg_header_adjust_offset(); //UART_PUTF("MessageType = %u\r\n", message_type); uint8_t string_offset_data = 0; /* UART_PUTS("sKK00RRRRGGMM.............Get\r\n"); UART_PUTS("sKK01RRRRGGMMDD...........Set\r\n"); UART_PUTS("sKK02RRRRGGMMDD...........SetGet\r\n"); UART_PUTS("sKK08GGMMDD...............Status\r\n"); UART_PUTS("sKK09SSSSPPPPPPEE.........Ack\r\n"); UART_PUTS("sKK0ASSSSPPPPPPEEGGMMDD...AckStatus\r\n"); */ // set header extension fields to the values given as hex string in the user input switch (message_type) { case MESSAGETYPE_GET: case MESSAGETYPE_SET: case MESSAGETYPE_SETGET: pkg_headerext_common_set_receiverid(hex_to_uint16((uint8_t *)cmdbuf, 5)); pkg_headerext_common_set_messagegroupid(hex_to_uint8((uint8_t *)cmdbuf, 9)); pkg_headerext_common_set_messageid(hex_to_uint8((uint8_t *)cmdbuf, 11)); string_offset_data = 12; break; case MESSAGETYPE_STATUS: pkg_headerext_common_set_messagegroupid(hex_to_uint8((uint8_t *)cmdbuf, 5)); pkg_headerext_common_set_messageid(hex_to_uint8((uint8_t *)cmdbuf, 7)); string_offset_data = 8; break; case MESSAGETYPE_ACK: pkg_headerext_common_set_acksenderid(hex_to_uint16((uint8_t *)cmdbuf, 5)); pkg_headerext_common_set_ackpacketcounter(hex_to_uint24((uint8_t *)cmdbuf, 9)); pkg_headerext_common_set_error(hex_to_uint8((uint8_t *)cmdbuf, 15)); // fallthrough! case MESSAGETYPE_ACKSTATUS: pkg_headerext_common_set_messagegroupid(hex_to_uint8((uint8_t *)cmdbuf, 17)); pkg_headerext_common_set_messageid(hex_to_uint8((uint8_t *)cmdbuf, 19)); string_offset_data = 20; break; } uint8_t data_len_raw = 0; // copy message data, which exists in all packets except in Get and Ack packets if ((message_type != MESSAGETYPE_GET) && (message_type != MESSAGETYPE_ACK)) { uint8_t data_len_raw = (strlen(cmdbuf) - 1 - string_offset_data) / 2; //UART_PUTF("Data bytes = %u\r\n", data_len_raw); uint8_t start = __HEADEROFFSETBITS / 8; uint8_t shift = __HEADEROFFSETBITS % 8; // copy message data, using __HEADEROFFSETBITS value and string_offset_data for (i = 0; i < data_len_raw; i++) { uint8_t val = hex_to_uint8((uint8_t *)cmdbuf, string_offset_data + 2 * i + 1); array_write_UIntValue(start + i, shift, 8, val, bufx); } } // round packet length to x * 16 bytes uint8_t packet_len = ((uint16_t)__HEADEROFFSETBITS + (uint16_t)data_len_raw * 8) / 8; packet_len = ((packet_len - 1) / 16 + 1) * 16; // send packet which doesn't require an acknowledge immediately if ((message_type != MESSAGETYPE_GET) && (message_type != MESSAGETYPE_SET) && (message_type != MESSAGETYPE_SETGET)) { send_packet(aes_key_nr, packet_len); } else // enqueue request (don't send immediately) { // header size = 9 bytes! if (queue_request(pkg_headerext_common_get_receiverid(), message_type, aes_key_nr, bufx + 9, packet_len - 9)) { UART_PUTF("Request added to queue (%u bytes packet).\r\n", packet_len); } else { UART_PUTS("Warning! Request queue full. Packet will not be sent.\r\n"); } print_request_queue(); } // clear cmdbuf to receive more input from UART send_data_avail = false; rfm12_tick(); led_blink(200, 0, 1); } // flash LED every second to show the device is alive if (loop == 50) { led_blink(10, 10, 1); loop = 0; request_t* request = find_request_to_repeat(packetcounter + 1); if (request != 0) // if request to repeat was found in queue { UART_PUTS("Repeating request.\r\n"); send_packet((*request).aes_key, (*request).data_bytes + 9); // header size = 9 bytes! print_request_queue(); } // Auto-send something for debugging purposes... if (loop2 == 50) { //strcpy(cmdbuf, "s000102828300"); //send_data_avail = true; loop2 = 0; } else { loop2++; } } else { _delay_ms(20); } rfm12_tick(); loop++; process_rxbuf(); if (uart_timeout > 0) { uart_timeout--; if (uart_timeout == 0) { UART_PUTS("*** UART user timeout. Input was ignored. ***\r\n"); } } } // never called // aes256_done(&aes_ctx); }
/** * @brief Echo the data for the user supplied buffer with async support * * This function copies the request buffer to response buffer to show the * non-zero copy functionality and to show the async support by wait for the * flag and it got set in interrupt handler * * @param req_buf: Virtual address of the request buffer * @param req_buf_len: Request buffer length * @param res_buf: Virtual address of the response buffer * @param res_buf_len: Response buffer length * @param meta_data: Virtual address of the meta data of the encoded data * @param ret_res_buf_len: Return length of the response buffer * * @return SMC return codes: * SMC_SUCCESS: API processed successfully. \n * SMC_*: An implementation-defined error code for any other error. */ int process_otz_echo_async_send_cmd(void *req_buf, u32 req_buf_len, void *res_buf, u32 res_buf_len, struct otzc_encode_meta *meta_data, u32 *ret_res_buf_len) { echo_data_t echo_data; char *out_buf; int offset = 0, pos = 0, mapped = 0, type, out_len; int task_id; sw_tls *tls; struct echo_global *echo_global; task_id = get_current_task_id(); tls = get_task_tls(task_id); echo_global = (struct echo_global *)tls->private_data; if(!echo_global->data_available) { struct timer_event* tevent; timeval_t time; tevent = timer_event_create(&echo_task_handler,(void*)task_id); if(!tevent){ sw_printf("SW: Out of Memory : Cannot register Handler\n"); return SMC_ENOMEM; } /* Time duration = 100ms */ time.tval.nsec = 100000000; time.tval.sec = 0; struct sw_task* task = get_task(task_id); task->wq_head.elements_count = 0; INIT_LIST_HEAD(&task->wq_head.elements_list); task->wq_head.spin_lock.lock = 0; timer_event_start(tevent,&time); #ifdef ASYNC_DBG sw_printf("SW: Before calling wait event \n"); #endif sw_wait_event_async(&task->wq_head, echo_global->data_available, SMC_PENDING); #ifdef ASYNC_DBG sw_printf("SW: Coming out from wait event \n"); #endif } if(req_buf_len > 0) { while (offset <= req_buf_len) { if(decode_data(req_buf, meta_data, &type, &offset, &pos, &mapped, (void**)&out_buf, &out_len)) { return SMC_EINVAL_ARG; } else { if(type != OTZ_ENC_UINT32) return SMC_EINVAL_ARG; echo_data.len = *((u32*)out_buf); } if(decode_data(req_buf, meta_data, &type, &offset, &pos, &mapped, (void**)&out_buf, &out_len)) { return SMC_EINVAL_ARG; } else { if(type != OTZ_ENC_ARRAY) return SMC_EINVAL_ARG; sw_memcpy(echo_data.data, out_buf, echo_data.len); } break; } } offset = 0, pos = OTZ_MAX_REQ_PARAMS; if(res_buf_len > 0) { while (offset <= res_buf_len) { if(decode_data(res_buf, meta_data, &type, &offset, &pos, &mapped, (void**)&out_buf, &out_len)) { return SMC_EINVAL_ARG; } else { if(type != OTZ_ENC_ARRAY) return SMC_EINVAL_ARG; } sw_memcpy(out_buf, echo_data.data, echo_data.len); if(update_response_len(meta_data, pos, echo_data.len)) return SMC_EINVAL_ARG; break; } *ret_res_buf_len = echo_data.len; } /* sw_printf("SW: echo task data: %s\n", echo_data.data); */ /* sw_printf("SW: echo send cmd %s and len 0x%x strlen 0x%x\n", echo_data.data, echo_data.len, sw_strlen(echo_data.data)); */ return 0; }
int main ( void ) { uint8_t aes_key_nr; uint8_t loop = 0; uint8_t loop2 = 0; uint8_t data[22]; sbi(LED_DDR, LED_PIN); // delay 1s to avoid further communication with uart or RFM12 when my programmer resets the MC after 500ms... _delay_ms(1000); request_queue_init(); // read packetcounter, increase by cycle and write back packetcounter = eeprom_read_dword((uint32_t*)EEPROM_POS_PACKET_COUNTER) + PACKET_COUNTER_WRITE_CYCLE; eeprom_write_dword((uint32_t*)0, packetcounter); uart_init(true); UART_PUTS ("\r\n"); UART_PUTS ("Open Home Control Base Station V1.0\r\n"); UART_PUTS ("(c) 2012 Uwe Freese, www.open-home-control.com\r\n"); UART_PUTF ("Packet counter: %lu\r\n", packetcounter); UART_PUTS ("Waiting for incoming data. Press h for help.\r\n"); rfm12_init(); sei(); // ENCODE TEST /* uint8_t testlen = 64; eeprom_read_block (aes_key, (uint8_t *)EEPROM_POS_AES_KEY, 32); UART_PUTS("Using AES key "); printbytearray((uint8_t *)aes_key, 32); UART_PUTS("Before encryption: "); printbytearray(bufx, testlen); unsigned long crc = crc32(bufx, testlen); UART_PUTF("CRC32 is %lx (added as last 4 bytes)\r\n", crc); UART_PUTS("1\r\n"); crc = crc32(bufx, testlen - 4); UART_PUTS("2\r\n"); setBuf32(testlen - 4, crc); UART_PUTS("Before encryption (CRC added): "); printbytearray(bufx, testlen); UART_PUTS("1\r\n"); uint8_t aes_byte_count = aes256_encrypt_cbc(bufx, testlen); UART_PUTS("2\r\n"); UART_PUTS("After encryption: "); printbytearray(bufx, aes_byte_count); UART_PUTF("String len = %u\r\n", aes_byte_count); UART_PUTS("1\r\n"); aes256_decrypt_cbc(bufx, aes_byte_count); UART_PUTS("2\r\n"); UART_PUTS("After decryption: "); printbytearray(bufx, testlen); crc = getBuf32(testlen - 4); UART_PUTF("CRC32 is %lx (last 4 bytes from decrypted message)\r\n", crc); printbytearray(bufx, testlen); UART_PUTS("After decryption (CRC removed): "); printbytearray(bufx, testlen); UART_PUTF("String len = %u\r\n", testlen); while(1); */ while (42) { if (rfm12_rx_status() == STATUS_COMPLETE) { uint8_t len = rfm12_rx_len(); if ((len == 0) || (len % 16 != 0)) { UART_PUTF("Received garbage (%u bytes not multiple of 16): ", len); printbytearray(bufx, len); } else // try to decrypt with all keys stored in EEPROM { uint32_t assumed_crc; uint32_t actual_crc; for(aes_key_nr = 0; aes_key_nr < AES_KEY_EEPROM_COUNT ; aes_key_nr++) { //strncpy((char *)bufx, (char *)rfm12_rx_buffer(), len); memcpy(bufx, rfm12_rx_buffer(), len); /*if (aes_key_nr == 0) { UART_PUTS("Before decryption: "); printbytearray(bufx, len); }*/ eeprom_read_block (aes_key, (uint8_t *)(EEPROM_POS_AES_KEY + aes_key_nr * 32), 32); //UART_PUTS("Trying AES key "); //printbytearray((uint8_t *)aes_key, 32); aes256_decrypt_cbc(bufx, len); //UART_PUTS("Decrypted bytes: "); //printbytearray(bufx, len); assumed_crc = getBuf32(len - 4); actual_crc = crc32(bufx, len - 4); //UART_PUTF("Received CRC32 would be %lx\r\n", assumed_crc); //UART_PUTF("Re-calculated CRC32 is %lx\r\n", actual_crc); if (assumed_crc == actual_crc) { //UART_PUTS("CRC correct, AES key found!\r\n"); UART_PUTF("Received (AES key %u): ", aes_key_nr); printbytearray(bufx, len - 4); decode_data(len - 4); break; } } if (assumed_crc != actual_crc) { UART_PUTS("Received garbage (CRC wrong after decryption).\r\n"); } UART_PUTS("\r\n"); } //uart_hexdump((char *)bufcontents, rfm12_rx_len()); //UART_PUTS("\r\n"); // tell the implementation that the buffer can be reused for the next data. rfm12_rx_clear(); } // send data, if waiting in send buffer if (send_data_avail) { uint8_t i; uint8_t data_len_raw = strlen(sendbuf) / 2 - 2; // round data length to 6 + 16 bytes (including padding bytes) uint8_t data_len = (((data_len_raw + 9) / 16) + 1) * 16 - 10; // set aes key nr aes_key_nr = hex_to_uint8((uint8_t *)sendbuf, 0); //UART_PUTF("AES KEY = %u\r\n", aes_key_nr); // set command id uint8_t command_id = hex_to_uint8((uint8_t *)sendbuf, 2); // set data for (i = 0; i < data_len_raw; i++) { data[i] = hex_to_uint8((uint8_t *)sendbuf, 4 + 2 * i); } // set padding bytes for (i = data_len_raw; i < data_len; i++) { data[i] = 0; } // send status packet immediately (command IDs are less than 128) if (command_id < 128) { // set command id bufx[5] = command_id; // set data memcpy(bufx + 6, data, data_len); send_packet(aes_key_nr, data_len); } else // enqueue request (don't send immediately) { if (queue_request(data[0], command_id, aes_key_nr, data + 1)) { UART_PUTS("Adding request to queue.\r\n"); } else { UART_PUTS("Warning! Request queue full. Packet will not be sent.\r\n"); } print_request_queue(); } // clear send text buffer send_data_avail = false; rfm12_tick(); led_blink(200, 0, 1); } // flash LED every second to show the device is alive if (loop == 50) { led_blink(10, 10, 1); loop = 0; if (set_repeat_request(packetcounter + 1)) // if request to repeat was found in queue { UART_PUTS("Repeating request.\r\n"); send_packet(0, 6); print_request_queue(); } // Auto-send something for debugging purposes... if (loop2 == 50) { //strcpy(sendbuf, "008c0001003d"); //send_data_avail = true; loop2 = 0; } else { loop2++; } } else { _delay_ms(20); } rfm12_tick(); loop++; process_rxbuf(); if (uart_timeout > 0) { uart_timeout--; if (uart_timeout == 0) { UART_PUTS("*** UART user timeout. Input was ignored. ***\r\n"); } } } // never called // aes256_done(&aes_ctx); }
int main (int argc, char *argv[]) { int erasures[16]; int nerasures = 0; char* filename = argv[1]; char command[100]; printf("reading the original file %s\n",argv[1]); //filename = argv[1]; sprintf(command,"md5 %s",argv[1]); system(command); /* Initialization the ECC library */ initialize_ecc (); //Open file file = fopen(argv[1], "r"); if (!file) { fprintf(stderr, "Unable to open file %s", argv[1]); exit(1); } //Get file length fseek(file, 0, SEEK_END); fileLen=ftell(file); fseek(file, 0, SEEK_SET); //Allocate memory buffer=(unsigned char *)malloc(fileLen+1); if (!buffer) { fprintf(stderr, "Memory error!"); fclose(file); exit(2); } //Read file contents into buffer fread(buffer, fileLen, 1, file); fclose(file); long i = fileLen; long pos = 0; int writeFlag = TRUE; strcat(filename,".encode"); printf("----------------------------------------------\n"); printf("encoding the original file into %s\n",filename); while (i>0) { //system(command); int msgLen; if (i>256-NPAR) { msgLen = 256-NPAR; } else { msgLen = i; } unsigned char msg[msgLen]; int k; for(k=0;k<msgLen;k++) { msg[k] = buffer[pos]; pos++; } encode_data(msg, sizeof(msg), codeword); if (writeFlag) { file = fopen(filename, "w+"); writeFlag = FALSE; } else { file = fopen(filename, "a+"); } fwrite(codeword, msgLen+NPAR, 1, file); fclose(file); i = i - msgLen; } free(buffer); sprintf(command,"md5 %s",filename); system(command); file = fopen(filename, "r"); if (!file) { fprintf(stderr, "Unable to open file %s", filename); exit(1); } //Get file length fseek(file, 0, SEEK_END); fileLen=ftell(file); fseek(file, 0, SEEK_SET); //Allocate memory buffer=(unsigned char *)malloc(fileLen+1); if (!buffer) { fprintf(stderr, "Memory error!"); fclose(file); exit(2); } //Read file contents into buffer fread(buffer, fileLen, 1, file); fclose(file); i = fileLen; pos = 0; writeFlag = TRUE; strcat(filename,".corrupt"); printf("----------------------------------------------\n"); printf("making some errors and write into the file %s\n",filename); int k; for(k = 0;k<10;k++) { long h = rand()%fileLen; buffer[h] = buffer[h] % 20; } file = fopen(filename, "w+"); fwrite(buffer, fileLen, 1, file); fclose(file); free(buffer); sprintf(command,"md5 %s",filename); system(command); file = fopen(filename, "r"); if (!file) { fprintf(stderr, "Unable to open file %s", filename); exit(1); } //Get file length fseek(file, 0, SEEK_END); fileLen=ftell(file); fseek(file, 0, SEEK_SET); //Allocate memory buffer=(unsigned char *)malloc(fileLen+1); if (!buffer) { fprintf(stderr, "Memory error!"); fclose(file); exit(2); } //Read file contents into buffer fread(buffer, fileLen, 1, file); fclose(file); i = fileLen; pos = 0; writeFlag = TRUE; strcat(filename,".recover"); printf("----------------------------------------------\n"); printf("recovering corrupted file into %s\n",filename); while (i>0) { int msgLen; if (i>256) { msgLen = 256; } else { msgLen = i; } unsigned char msg[msgLen]; int k; for(k=0;k<msgLen;k++) { msg[k] = buffer[pos]; pos++; } decode_data(msg, msgLen); if (check_syndrome () != 0) { correct_errors_erasures (msg,msgLen,nerasures,erasures); } if (writeFlag) { file = fopen(filename, "w+"); writeFlag = FALSE; } else { file = fopen(filename, "a+"); } fwrite(msg, msgLen-NPAR, 1, file); fclose(file); i = i - msgLen; } sprintf(command,"md5 %s",filename); system(command); free(buffer); exit(0); }
/** * @brief Test the mutex operations * * This function tests the functionality of mutex and semaphores * * @param req_buf: Virtual address of the request buffer * @param req_buf_len: Request buffer length * @param res_buf: Virtual address of the response buffer * @param res_buf_len: Response buffer length * @param meta_data: Virtual address of the meta data of the encoded data * @param ret_res_buf_len: Return length of the response buffer * * @return SMC return codes: * SMC_SUCCESS: API processed successfully. \n * SMC_*: An implementation-defined error code for any other error. */ int process_otz_mutex_test_cmd(void *req_buf, u32 req_buf_len, void *res_buf, u32 res_buf_len, struct otzc_encode_meta *meta_data, u32 *ret_res_buf_len) { otz_mutex_test_data_t otz_mutex_test_data; unsigned char *out_buf; int offset = 0, pos = 0, mapped = 0, type, out_len=0; while (offset <= req_buf_len) { if(decode_data(req_buf, meta_data, &type, &offset, &pos, &mapped, (void**)&out_buf, &out_len)) { return SMC_EINVAL_ARG; } if(type != OTZ_ENC_UINT32) { return SMC_EINVAL_ARG; } otz_mutex_test_data.len = *((u32*)out_buf); if(decode_data(req_buf, meta_data, &type, &offset, &pos, &mapped, (void**)&out_buf, &out_len)) { return SMC_EINVAL_ARG; } if(type != OTZ_ENC_ARRAY) { return SMC_EINVAL_ARG; } if(out_len < DATA_BUF_LEN) { sw_memcpy(otz_mutex_test_data.data, out_buf, out_len); } else { return(SMC_ENOMEM); } break; } #ifndef CONFIG_SW_ELF_LOADER_SUPPORT sw_printf("SW: Attempting to lock the variable \n"); #endif if(sw_mutex_lock(&g_otz_mutex) == OTZ_INVALID) { #ifndef CONFIG_SW_ELF_LOADER_SUPPORT sw_printf("SW: Unable to lock mutex. It is invalid \n"); #endif goto handle_error; } #ifndef CONFIG_SW_ELF_LOADER_SUPPORT sw_printf("SW: Lock successful. Trying to lock it one more time \n"); #endif if(sw_mutex_trylock(&g_otz_mutex) == OTZ_BUSY) { #ifndef CONFIG_SW_ELF_LOADER_SUPPORT sw_printf("SW: Mutex already locked. We cannot lock it anymore !! \n"); #endif } sw_mutex_unlock(&g_otz_mutex); #ifndef CONFIG_SW_ELF_LOADER_SUPPORT sw_printf("SW: Unlock successful. Trying to lock it one more time \n"); #endif if(sw_mutex_trylock(&g_otz_mutex) == OTZ_BUSY) { #ifndef CONFIG_SW_ELF_LOADER_SUPPORT sw_printf("SW: Error while unlocking the mutex !! \n"); #endif goto handle_error; } #ifndef CONFIG_SW_ELF_LOADER_SUPPORT sw_printf("SW: Going to sleep \n"); #endif usleep(10); #ifndef CONFIG_SW_ELF_LOADER_SUPPORT sw_printf("SW: Second time locking successful \n"); #endif sw_mutex_unlock(&g_otz_mutex); handle_error: offset = 0, pos = OTZ_MAX_REQ_PARAMS; while (offset <= res_buf_len) { if(decode_data(res_buf, meta_data, &type, &offset, &pos, &mapped, (void**)&out_buf, &out_len)) { return SMC_EINVAL_ARG; } if(type != OTZ_ENC_ARRAY) { return SMC_EINVAL_ARG; } if(out_len >= otz_mutex_test_data.len) { sw_memcpy(out_buf,otz_mutex_test_data.response, otz_mutex_test_data.len); if(update_response_len(meta_data, pos, otz_mutex_test_data.len)) { return SMC_EINVAL_ARG; } } else { return(SMC_ENOMEM); } break; } *ret_res_buf_len = otz_mutex_test_data.len; return 0; }