int CrcManager::write_crc_file(char const *filename) // return 0 on failure { const size_t msgsize = 100; char msg[msgsize]; snprintf(msg, msgsize, "%s", symbol_str("calc_crc")); // this may take some time, show the user a status indicator if (stat_man) stat_man->push(msg,NULL); int i,total=0; for (i=0; i<total_files; i++) { int failed=0; get_crc(i,failed); if (failed) { jFILE *fp=new jFILE(get_filename(i),"rb"); if (!fp->open_failure()) { set_crc(i,crc_file(fp)); total++; } delete fp; } else total++; if (stat_man) stat_man->update(i*100/total_files); } if (stat_man) stat_man->pop(); jFILE *fp=new jFILE(NET_CRC_FILENAME,"wb"); if (fp->open_failure()) { delete fp; return 0; } fp->write_uint16(total); total=0; for (i=0; i<total_files; i++) { uint32_t crc; int failed=0; crc=get_crc(i,failed); if (!failed) { fp->write_uint32(crc); uint8_t len=strlen(get_filename(i))+1; fp->write_uint8(len); fp->write(get_filename(i),len); total++; } } delete fp; return 1; }
/* * write .nvm and .pib to flash */ static int plc_write_to_flash(char *nvm_path, char *pib_path) { int fd, fl; plc_image_header *hdr = &header; char cmd[128]; memset(hdr, 0, sizeof(plc_image_header)); hdr->magic = PLC_MAGIC; // get length and crc of .nvm if (get_crc(nvm_path, &hdr->nvm_size, &hdr->nvm_crc)) { fprintf(stderr, "%s: Can't check crc of %s\n", __func__, nvm_path); return -1; } // get length and crc of .pib if (get_crc(pib_path, &hdr->pib_size, &hdr->pib_crc)) { fprintf(stderr, "%s: Can't check crc of %s\n", __func__, pib_path); return -1; } // create header hdr->hdr_crc = crc_calc(0, (const char *)hdr, sizeof(plc_image_header)); if ((fd = open(HDR_PATH, O_RDWR|O_CREAT, 0666)) < 0) { fprintf(stderr, "%s: Can't open %s\n", __func__, HDR_PATH); return -1; } write(fd, hdr, sizeof(plc_image_header)); close(fd); // write to plc partition while (1) { if ((fl = open(PLC_LOCK_FILE, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600)) >= 0) { sprintf(cmd, "cat %s %s %s > %s", HDR_PATH, nvm_path, pib_path, IMAGE_PATH); system(cmd); sprintf(cmd, "mtd-write -i %s -d %s", IMAGE_PATH, PLC_MTD_NAME); system(cmd); close(PLC_LOCK_FILE); unlink(PLC_LOCK_FILE); break; } else { dbg("%s: PLC file lock! Try again after waiting 1 sec\n", __func__); sleep(1); } } unlink(HDR_PATH); unlink(IMAGE_PATH); return 0; }
void PrivateFileInfoHandler::do_read(PtrTcpConnection tcp_connection) { if (total_bytes_read < 4) { tcp_connection->do_read(boost::asio::buffer(buffer_.data()+total_bytes_read, 4-total_bytes_read)); return; } // then read file name if (filename_length<=0) { memcpy(&filename_length, buffer_.data(), sizeof(filename_length)); } if (filename_length + 4 > total_bytes_read) tcp_connection->do_read(boost::asio::buffer(buffer_.data()+total_bytes_read, filename_length+4-total_bytes_read)); else { // file name is available FileInfo file_info; memset(&file_info, 0, sizeof(file_info)); buffer_[filename_length+4] = 0; file_name = buffer_.data() + 4; int ret = get_file_time(file_name.c_str(), file_info); // get CRC32 ret = get_crc(file_name.c_str(), file_info.crc32); memcpy(buffer_.data(), &file_info, sizeof(file_info)); do_write(tcp_connection); } }
static void flash_write(FlashIO* io, FlashWrite* fc) { FlashWritten info; info.cmd = FLASH_WRITTEN; info.req_id = fc->req_id; info.addr = fc->addr; info.bytes = 0; // Do the write info.bytes = flash_save(io, fc->addr, fc->bytes, fc->data); #if defined(ALLOW_VERBOSE) if (debug_fn) { char buff[24]; snprintf(buff, sizeof(buff), "flash_write(r=%d,%ld,%d)\r\n", (int) info.req_id, info.addr, info.bytes); debug(buff); } #endif // ALLOW_VERBOSE // CRC the EEPROM that we've just written info.crc = get_crc(io, fc->addr, fc->bytes); send_flash_message(& info, sizeof(info)); }
static void flash_slot(FlashIO* io, FlashSlot* fc) { #if defined(ALLOW_VERBOSE) if (debug_fn) { char buff[32]; snprintf(buff, sizeof(buff), "flash_record(r=%d,%d)\r\n", (int) fc->req_id, fc->slot); debug(buff); } #endif // ALLOW_VERBOSE // Write Record const uint16_t size = sizeof(fc->entry); const uint32_t offset = fc->slot * size; FlashWritten info; info.cmd = FLASH_WRITTEN; info.req_id = fc->req_id; info.addr = offset; info.bytes = 0; // Do the write if (fc->slot <= MAX_SLOTS) { info.bytes = flash_save(io, offset, size, (uint8_t*) & fc->entry); // CRC the EEPROM that we've just written info.crc = get_crc(io, offset, size); } send_flash_message(& info, sizeof(info)); }
static void flash_crc_req(FlashIO* io, FlashCrcReq* fc) { FlashCrc info; info.cmd = FLASH_CRC; info.req_id = fc->req_id; info.addr = fc->addr; info.bytes = fc->bytes; #if defined(ALLOW_VERBOSE) if (debug_fn) { char buff[32]; snprintf(buff, sizeof(buff), "flash_crc(r=%d,%ld,%d,", (int) fc->req_id, info.addr, info.bytes); debug(buff); } #endif // ALLOW_VERBOSE info.crc = get_crc(io, fc->addr, fc->bytes); #if defined(ALLOW_VERBOSE) if (debug_fn) { char buff[32]; snprintf(buff, sizeof(buff), "%X)\r\n", info.crc); debug(buff); } #endif // ALLOW_VERBOSE send_flash_message(& info, sizeof(info)); }
void start_link_server(int node_id) { int sock_des; struct sockaddr_in server; char buffer[LINK_LAYER_RECV_SIZE_MAX]; int recv_size; uint32_t *rec_crc; uint32_t packet_crc; struct hostent *hp; int node_index; server.sin_family = AF_INET; node_index = find_node_by_id(node_id); if ( node_index != NOT_FOUND) { hp = gethostbyname(cfg_items[node_index].node_name); bcopy(hp->h_addr,&(server.sin_addr.s_addr),hp->h_length); #ifdef DEBUG printf(" node_index = %d " , node_index); printf(" port = %d" ,(cfg_items[node_index].udp_port)); #endif server.sin_port = htons(cfg_items[node_index].udp_port); } else { #ifdef DEBUG printf("\n Node id not found = %d \n" , node_id); #endif } sock_des = socket(AF_INET , SOCK_DGRAM , 0); if ( bind(sock_des,( struct sockaddr *) &server , sizeof(server)) < 0 ) { perror("Bind failed .. .") ; printf("\n bind failed ... "); } while (TRUE) { recv_size = recv ( sock_des , buffer , sizeof(buffer) , 0 ); packet_crc = get_crc((char *)buffer + LINK_LAYER_HEADER_SIZE ,recv_size - LINK_LAYER_HEADER_SIZE); rec_crc = (uint32_t *) get_packet_item(buffer , LINK_CKSUM_OFFSET , LINK_CKSUM_SIZE ); if ( *rec_crc == packet_crc ) { send_packet_to_network_layer(buffer,recv_size); } else { fprintf(stderr ,"\n CRC check failed , packet dropped !"); fprintf(stderr , "Rec length = %d " ,recv_size ); fprintf(stderr , " Packet crc = %u rec crc = %u " , packet_crc , *rec_crc); } } }
void link_send_buffer(void *buffer , int len , int node_id) { int sock_des; struct sockaddr_in server; struct hostent *hp; int node_index; uint32_t crc; void *snd_buffer; server.sin_family = AF_INET; snd_buffer = expand_packet(&buffer , len , LINK_LAYER_HEADER_SIZE); crc = get_crc((char *) snd_buffer + LINK_LAYER_HEADER_SIZE , len); pack_into_packet(snd_buffer , LINK_CKSUM_OFFSET , &crc , LINK_CKSUM_SIZE); node_index = find_node_by_id(node_id); if ( node_index != NOT_FOUND) { hp = gethostbyname(cfg_items[node_index].node_name); bcopy(hp->h_addr,&(server.sin_addr.s_addr),hp->h_length); server.sin_port = htons(cfg_items[node_index].udp_port); } sock_des = socket(AF_INET , SOCK_DGRAM , 0); bind(sock_des,( struct sockaddr *) &server , sizeof(server)); sendto_garbled( sock_des , snd_buffer , len + LINK_LAYER_HEADER_SIZE,0,(struct sockaddr *)&server, sizeof(server)); }
/** * Diff two file listings */ tFileMap GetDiff( const launcher::FileList &oldList, const launcher::FileList &newList) { Trace("Computing patch list"); Log(LL::Info) << "Current Version: " << oldList.get_version_id() << " [" << oldList.get_crc() << "]" << std::endl; Log(LL::Info) << "Server Version : " << newList.get_version_id() << " [" << newList.get_crc() << "]" << std::endl; tFileMap rVal; for (auto file = newList.get_files_begin(); file != newList.get_files_end(); ++file) { rVal[ file->get_filename() ] = *file; } for (auto file = oldList.get_files_begin(); file != oldList.get_files_end(); ++file) { auto itr = rVal.find(file->get_filename()); if (itr == rVal.end()) { continue; } if (itr->second.get_crc() != file->get_crc()) { continue; } rVal.erase(itr); } return rVal; }
/* Check for the presence of a card. If found, and if supplied buffer is sufficiently large, fill in buffer with a binary ID string, and return the length of it. Else, return 0. */ uint8_t check_mfrc522(char *outbuf, uint8_t outbufsize) { uint8_t buf1[4]; uint8_t buf2[2]; uint8_t buf3[5]; uint8_t rx_bits; uint8_t err; uint8_t i, outlen = 0; // char txtbuf[32]; if (outbufsize < 10) return 0; /* Check for card type. */ mfrc522_write_reg(REG_BitFraming, 7); buf1[0] = 0x26; err = mfrc522_trx(buf1, 1, buf2, 2, &rx_bits); if (err) goto end; if (rx_bits != 16) goto end; // sprintf(txtbuf, "Typ: %02x %02x\n", buf2[0], buf2[1]); // serial_print(txtbuf); /* Read card ID number. */ mfrc522_write_reg(REG_BitFraming, 0); buf1[0] = 0x93; buf1[1] = 0x20; err = mfrc522_trx(buf1, 2, buf3, 5, &rx_bits); if (err) goto end; /* Checksum. */ if (buf3[0] ^ buf3[1] ^ buf3[2] ^ buf3[3] ^ buf3[4]) goto end; // sprintf(txtbuf, "Num: %02x %02x %02x %02x %02x\n", // buf3[0], buf3[1], buf3[2], buf3[3], buf3[4]); // serial_print(txtbuf); /* We saw a card; format a 10-byte ID string from type / serial number. */ outbuf[outlen++] = 'M'; outbuf[outlen++] = 'F'; outbuf[outlen++] = 'R'; for (i = 0; i < 2; ++i) outbuf[outlen++] = buf2[i]; for (i = 0; i < 5; ++i) outbuf[outlen++] = buf3[i]; end: /* Go to halt/hibernation. */ buf1[0] = 0x50; buf1[1] = 0x0; get_crc(buf1, 2, buf1+2); mfrc522_trx(buf1, 4, buf3, 5, &rx_bits); return outlen; }
/* Receive a Topfield protocol packet. * Returns a negative number if the packet read failed for some reason. */ ssize_t get_tf_packet(int fd, struct tf_packet * packet) { __u8 *buf = (__u8 *) packet; int r; trace(3, fprintf(stderr, "get_tf_packet\n")); r = usb_bulk_read(fd, 0x82, buf, MAXIMUM_PACKET_SIZE, TF_PROTOCOL_TIMEOUT); if(r < 0) { fprintf(stderr, "USB read error: %s\n", strerror(errno)); return -1; } if(r < PACKET_HEAD_SIZE) { fprintf(stderr, "Short read. %d bytes\n", r); return -1; } /* Send SUCCESS as soon as we see a data transfer packet */ if(DATA_HDD_FILE_DATA == get_u32_raw(&packet->cmd)) { send_success(fd); } swap_in_packet(packet); { __u16 crc; __u16 calc_crc; __u16 len = get_u16(&packet->length); if(len < PACKET_HEAD_SIZE) { fprintf(stderr, "Invalid packet length %04x\n", len); return -1; } crc = get_u16(&packet->crc); calc_crc = get_crc(packet); /* Complain about CRC mismatch */ if(crc != calc_crc) { fprintf(stderr, "WARNING: Packet CRC %04x, expected %04x\n", crc, calc_crc); } } print_packet(packet, " IN<"); return r; }
/* Given a Topfield protocol packet, this function will calculate the required * CRC and send the packet out over a bulk pipe. */ ssize_t send_tf_packet(int fd, struct tf_packet *packet) { unsigned int pl = get_u16(&packet->length); ssize_t byte_count = (pl + 1) & ~1; trace(3, fprintf(stderr, "%s\n", __func__)); put_u16(&packet->crc, get_crc(packet)); print_packet(packet, "OUT>"); swap_out_packet(packet); return usb_bulk_write(fd, 0x01, (__u8 *) packet, byte_count, TF_PROTOCOL_TIMEOUT); }
/** * ReadSubfr3 function * The function decodes the 3rd subframe of the GPS navigation data * according to the IS-GPS-200E section IS-GPS-200E : 20.3.3.4.1 Content * of Subframes 2 and 3 and updates the Satellite structure, * identified by its pointer. * @param *Sat The pointer of the Satellite structure * @param *data The pointer of the 300 bits */ void ReadSubfr3(Satellite * Sat, char * data) { (*Sat).cic = get_cic((*Sat).subfr3); (*Sat).cis = get_cis((*Sat).subfr3); (*Sat).crc = get_crc((*Sat).subfr3); (*Sat).w = get_w((*Sat).subfr3); (*Sat).omega0 = get_omega0((*Sat).subfr3); (*Sat).omegadot = get_omegadot((*Sat).subfr3); (*Sat).i0 = get_i0((*Sat).subfr3); (*Sat).idot = get_idot((*Sat).subfr3); (*Sat).iode_s3 = get_iode_s3((*Sat).subfr3); }
void settings_write(void) { uint32_t chk = get_crc(); if (chk != settings.settings_words[USER_PAGE_CHECKSUM]) { settings.settings_words[USER_PAGE_CHECKSUM] = chk; settings.settings_words[BOOT_LOADER_CONFIGURATION] = 0x929E1424; // boot loader config word flashc_memcpy(AVR32_FLASHC_USER_PAGE, & settings, 512, TRUE); } }
uint32_t genfile_cache::convert_mod2crc(const llvm::Module *module, const std::string &options) { std::string llvm_ir; llvm::raw_string_ostream ostream(llvm_ir); llvm::WriteBitcodeToFile(module, ostream); ostream.str(); llvm_ir += options; return get_crc(llvm_ir); }
/* * check crc of file and header record * * fname: input, file name * crc: input, header record * * return * 1: match * 0: mismatch or fail */ static int match_crc(char *fname, unsigned int crc) { unsigned int len, checksum; if (get_crc(fname, &len, &checksum)) { fprintf(stderr, "%s: Can't check crc of %s\n", __func__, fname); return 0; } fprintf(stderr, "%s: crc %x/%x of %s\n", __func__, crc, checksum, fname); if (checksum != crc) { fprintf(stderr, "%s: %s crc mismatch!\n", __func__, fname); return 0; } return 1; }
int snmp_get_flashstatus (int32_t arg, uint8_t * res, int * res_len, int maxlen) { uint32_t chk = get_crc(); if (chk != settings.settings_words[USER_PAGE_CHECKSUM]) { res[0] = 1; // settings have changed } else { res[0] = 0; // settings are identical to flash } *res_len = 1; return 0; }
BindedChain* getBindedChainByAddress(RSSObject* addr){ std::string* address=addr->dynObjectByName("address"); uint domain_crc=get_crc(address->data(),address->length()); for(int i=0;i<binded_chains.size();i++){ if(binded_chains[i]->domain_address_crc==domain_crc){ if(binded_chains[i]->getChainsResponse->objectByName("address")->compare(addr)){ return binded_chains[i]; break; } } } RSSObject* getChainsRequest=new RSSObject(getDefinedStructs(),"getChainsRequest"); getChainsRequest->objectByName("address")->assign(addr); rsock->sendToRouteServer(RS_CMD_GETCHAINS_REQUEST,getChainsRequest); delete getChainsRequest; return NULL; }
void settings_init(void) { memcpy(& settings, (const void *) AVR32_FLASHC_USER_PAGE, 512); uint32_t chk = get_crc(); if (chk != settings.settings_words[USER_PAGE_CHECKSUM]) // checksum wrong, set default values { int i; memset (&settings, 0, 504); // fill user page with 0 for (i=0; i < NUM_LONG_VALUES; i++) { settings.s.long_values[i] = long_values_limits[i].init_value; } for (i=0; i < NUM_SHORT_VALUES; i++) { settings.s.short_values[i] = short_values_limits[i].init_value; } for (i=0; i < NUM_CHAR_VALUES; i++) { settings.s.char_values[i] = char_values_limits[i].init_value; } memset(settings.s.rpt1, ' ', CALLSIGN_LENGTH * NUM_RPT_SETTINGS); memset(settings.s.rpt2, ' ', CALLSIGN_LENGTH * NUM_RPT_SETTINGS); memset(settings.s.urcall, ' ', CALLSIGN_LENGTH * NUM_URCALL_SETTINGS); memset(settings.s.dprs_msg, ' ', DPRS_MSG_LENGTH); memset(settings.s.txmsg, ' ', TXMSG_LENGTH); memcpy(settings.s.my_callsign, "NOCALL ", CALLSIGN_LENGTH); memcpy(settings.s.my_ext, " ", CALLSIGN_EXT_LENGTH); memcpy(settings.s.rpt1, "DB0DF B", CALLSIGN_LENGTH); memcpy(settings.s.rpt2, "DB0DF G", CALLSIGN_LENGTH); memcpy(settings.s.urcall + (0*CALLSIGN_LENGTH), "CQCQCQ ", CALLSIGN_LENGTH); memcpy(settings.s.urcall + (1*CALLSIGN_LENGTH), " U", CALLSIGN_LENGTH); memcpy(settings.s.urcall + (2*CALLSIGN_LENGTH), "CQCQ DVR", CALLSIGN_LENGTH); memcpy(settings.s.qrg_tx, "430375000", QRG_LENGTH); memcpy(settings.s.qrg_rx, "430375000", QRG_LENGTH); } }
/* Given a Topfield protocol packet, this function will calculate the required * CRC and send the packet out over a bulk pipe. */ int send_tf_packet(libusb_device_handle* fd, struct tf_packet *packet) { unsigned int pl = get_u16(&packet->length); size_t byte_count = (pl + 1) & ~1; put_u16(&packet->crc, get_crc(packet)); if (verbose>2) print_packet(packet, "OUT>"); swap_out_packet(packet); if (fd==0) return -1; return usb_bulk_write(fd, 0x01, (__u8 *) packet, byte_count, default_timeout()); }
int snmp_set_flashstatus (int32_t arg, const uint8_t * req, int req_len) { if (req[ req_len - 1] == 2) // least significant byte == 2 { uint32_t chk = get_crc(); if (chk != settings.settings_words[USER_PAGE_CHECKSUM]) { settings.settings_words[USER_PAGE_CHECKSUM] = chk; settings.settings_words[BOOT_LOADER_CONFIGURATION] = 0x929E1424; // boot loader config word flashc_memcpy(AVR32_FLASHC_USER_PAGE, & settings, 512, TRUE); settings_set_home_ref(); } } return 0; }
void COil::P_ThreadSend() { byte bytLvl = 0; char szRecvBuf[1024] = {0}; char szSendBuf[1024] = {0}; DWORD dwRecvLen = 0; int iSendLen = 0; DWORD dwPushTm; DWORD dwBufSize = (DWORD)sizeof(szRecvBuf); while( !g_bProgExit ) { dwRecvLen = 0; memset(szRecvBuf, 0, sizeof(szRecvBuf)); // 先处理串口接收到的数据 if( !m_objRecvMng.PopData(bytLvl, dwBufSize, dwRecvLen, szRecvBuf, dwPushTm)) { if( dwRecvLen <= dwBufSize ) DealComFrame(szRecvBuf, (int)dwRecvLen); } // 再向串口发送数据 if( !m_objSendMng.PopData(bytLvl, dwBufSize, dwRecvLen, szRecvBuf, dwPushTm)) { szSendBuf[1] = 2; // 协议版本,固定取1 szSendBuf[2] = 4; // 外设编号,固定取4 szSendBuf[3] = 0; // 外设序号,固定取0 memcpy(szSendBuf+4, szRecvBuf, dwRecvLen); szSendBuf[0] = get_crc((byte*)szSendBuf+1, 3+dwRecvLen); iSendLen = 4+dwRecvLen; // 转义 iSendLen = TranData(szSendBuf, iSendLen); // 发送数据帧 ComWrite(szSendBuf, iSendLen); } usleep(50000); } }
GByteArray *JarFile::get_next_file_contents() { guint8 *bytes; GByteArray *gba = g_byte_array_new(); read_signature(); //get compressed size bytes = (guint8 *)g_malloc(sizeof(guint8) * 30); if (!read(bytes+4, 26)) { g_free(bytes); return NULL; } guint32 compressed_size = UNPACK_UB4(bytes, LOC_CSIZE); guint16 filename_length = UNPACK_UB2(bytes, LOC_FNLEN); guint16 eflen = UNPACK_UB2(bytes, LOC_EFLEN); guint16 flags = UNPACK_UB2(bytes, LOC_EXTRA); guint16 method = UNPACK_UB2(bytes, LOC_COMP); if (filename_length == 0) { g_byte_array_free(gba, TRUE); if (_last_filename != NULL) g_free(_last_filename); _last_filename = NULL; g_free(bytes); return NULL; } #ifdef DEBUG std::printf("Compressed size is %u\n", compressed_size); std::printf("Filename length is %hu\n", filename_length); std::printf("Extra field length is %hu\n", eflen); std::printf("Flags are %#hx\n", flags); std::printf("Compression method is %#hx\n", method); #endif guint32 crc = get_crc(bytes, flags); gchar *filename = (gchar *)read_filename(filename_length); g_free(bytes); if (filename == NULL) return NULL; if (_last_filename != NULL) g_free(_last_filename); _last_filename = filename; //check if this is a directory and skip char *c_ptr; if ((c_ptr = std::strrchr(filename, '/')) != NULL) { if (*(++c_ptr) == '\0') { return NULL; } } if (!check_compression_method(method, flags)) { std::fprintf(stderr, "error in jar file\n"); return NULL; } if (method == 8 || flags & 0x0008) { unsigned int file_length = 0;//uncompressed file length lseek(fd, eflen, SEEK_CUR); guint8 *file_data = get_compressed_file(compressed_size, file_length, crc, flags); if (file_data == NULL) { g_byte_array_free(gba, FALSE); return NULL; } g_byte_array_append(gba, file_data, file_length); } else if (method == 0) { guint8 *file_data = get_uncompressed_file(compressed_size, crc, eflen, flags); if (file_data == NULL) { g_byte_array_free(gba, TRUE); return NULL; } g_byte_array_append(gba, file_data, compressed_size); } else { lseek(fd, compressed_size+eflen, SEEK_CUR); g_byte_array_free(gba, FALSE); return NULL; } return gba; }
/** return crc check result When you have finished reading the compressed data, call read_footer to read the uncompressed data crc. This method compares it to the crc of the uncompressed data. \return true if crc check is succesful */ bool check_crc() const { return get_crc() == m_gzip_crc;};
void receiver(){ while(rsock->receivePacket()){ RSSObject* o=NULL; rs_cmd_t cmd_id=rsock->getLastCmd(); if(rsock->isLastPackedFromRouteServer()){ if((cmd_id==RS_CMD_GETCHAINS_RESPONSE)&&(o=rsock->getLastPackedDataAsType("getChainsResponse"))){ printf("getChainsResponse\n"); RSSObject* addr_o=o->objectByName("address"); std::string* addr=addr_o->dynObjectByName("address"); uint addr_crc=get_crc(addr->data(),addr->length()); BindedChain* bc=NULL; if(o->uintObjectByName("status")==RS_GETCHAINS_RESPONSE_OK){ inc_binded(); printf("RS_GETCHAINS_RESPONSE_OK. RA=");print_ip4(*(in_addr*)&binded_ip);printf(" \n"); bc=new BindedChain; bc->getChainsResponse=new RSSObject(getDefinedStructs(),"getChainsResponse"); memcpy(&bc->local_addr,&binded_ip[0],4); bc->domain_address_crc=addr_crc; bc->getChainsResponse->assign(o); binded_chains.push_back(bc); } for(int i=0;i<dns_requests.size();i++){ dns_requests_t* rt=dns_requests[i]; if(rt->domain_address_crc==addr_crc){ if(rt->address->compare(addr_o)){ if(bc && o->uintObjectByName("status")==RS_GETCHAINS_RESPONSE_OK){ sendDNSResponse(rt,&bc->local_addr); }else{ sendDNSResponse(rt,NULL); } free_dns_requests_t(rt); dns_requests.erase(dns_requests.begin()+i); break; } } } }else if((cmd_id==RS_CMD_SETCHAINS_RESPONSE)&&(o=rsock->getLastPackedDataAsType("setChainsResponse"))){ printf("setChainsResponse\n"); if(o->objectByName("address")->uintObjectByName("type")==ADDR_TYPE_DOMAIN){ std::string *sstr=o->objectByName("address")->dynObjectByName("address"); for(int i=0;i<registred_clients.size();i++){ if(*(registred_clients.at(i)->local_domain)==*sstr){ registred_clients.at(i)->state=CLIENT_STATE_REGISTRED; break; } } } }else if((cmd_id==RS_CMD_ONDEVICECONNECT_RESPONSE)&&(o=rsock->getLastPackedDataAsType("onDeviceConnectResponse"))){ printf("onDeviceConnectResponse\n"); if(o->uintObjectByName("status")==RS_ONDEVICECONNECT_RESPONSE_OK){ printf("RS Register Success\n"); if(my_address){delete my_address;} my_address=o->objectByName("you_address")->copy(); RSSObject* os = new RSSObject(getDefinedStructs(),"getDevicesRequest"); os->setUintObjectByName("max_count",10); rsock->sendToRouteServer(RS_CMD_GETDEVICES_REQUEST,os); }else{ printf("RS Register Error\n"); } }else if((cmd_id==RS_CMD_GETDEVICES_RESPONSE)&&(o=rsock->getLastPackedDataAsType("getDevicesResponse"))){ printf("getDevicesResponse\n"); //clearing old device list for(int i=0;i<devices.size();i++){ delete devices[i]; } devices.clear(); //adding new device list std::vector<RSSObject*> * rd; rd=o->arrayObjectByName("devices"); if(rd){ for(int i=0;i<rd->size();i++){ RSSObject* no=(*rd)[i]->copy(); if(no){ devices.push_back(no); } } } } }else{ //end of from RouteServer. //then from devices if((cmd_id==RS_CMD_SEND_PACKET)&&(o=rsock->getLastPackedDataAsType("data_packet_t"))){ //o->printDump(""); apply_and_route_rss_packet(o,true); } }//end of from devices done: if(o){ delete o; } }//while receive packet }
/********************************************** 函数说明:更新ubl函数。成功返回0,返回其他 值都是错误的! **********************************************/ int update_ubl(struct ys_usb_handle *handle,const char *filepath) { FILE *fp; int actual_length; unsigned int FileSize,ret; unsigned int headersize,num,count,length; unsigned int SizeperSend = 400; unsigned int *head_ptr; unsigned char *data,rxbuf[1]; unsigned int magic; #if 0 unsigned char *temp,image_crc; int k; #endif fp=fopen(filepath,"r"); if(fp==NULL){ ysprint("%s open failed!",filepath); return(-20); } fread(&magic,1,4,fp); if(magic!=0x41504954){ ysprint("File type is wrong! Filepath:%s,magic = %x\n",filepath,magic); fclose(fp); sleep(1); return(-10); } // goto start of file fseek(fp,0,SEEK_SET); // read file size fseek(fp,0,SEEK_END); FileSize = ftell(fp); /*if(FileSize>65535){ ysprint("FILE:%s is too large!\n",filepath); return -5; }*/ #if 0 ysprint("FileSize = %d\n",FileSize); // goto start of file fseek(fp,0,SEEK_SET); temp = (unsigned char *)malloc(FileSize); fread(temp,1,FileSize,fp); image_crc = get_crc(temp,FileSize); ysprint("image_crc = %d\n",image_crc); ysprint("image begin\n"); for(k=0;k<FileSize;k++){ ysprint("%d\n",temp[k]); } ysprint("image end\n"); free(temp); temp = NULL; #endif length = FileSize%SizeperSend; if(length==0) length = FileSize/SizeperSend; else length = FileSize/SizeperSend + 1; // goto start of file fseek(fp,0,SEEK_SET); headersize = sizeof(struct usb_app_header); data = (unsigned char *)malloc(SizeperSend+headersize); if(data==NULL){ //ysprint(""); return -1; } head_ptr = (unsigned int *)data; num = 0; count = 0; while(1) { num++; memset(data,0,SizeperSend+headersize); head_ptr[0] = CMD_UPDATE_UBL; head_ptr[1] = num; head_ptr[2] = length; head_ptr[3] = FileSize; if(FileSize-count>SizeperSend) { fread(data+headersize,1,SizeperSend,fp); head_ptr[4] = get_crc(data+headersize,SizeperSend); usb_write(handle,data,SizeperSend+headersize); count += SizeperSend; } else { fread(data+headersize,1,FileSize-count,fp); head_ptr[4] = get_crc(data+headersize,FileSize-count); usb_write(handle,data,FileSize-count+headersize); break; } } free(data); data = NULL; fclose(fp); //等待dsp返回 ret = libusb_bulk_transfer(handle->libusb_handle,handle->Endpoint_in,rxbuf,sizeof(rxbuf),&actual_length,100); if(ret<0){ return ret; }else{ return rxbuf[0]; } }
/********************************************** 函数说明:USB写函数,成功返回0,失败返回负数。count 是要写的字节数。支持多个线程同时写操作。 **********************************************/ int usb_write(struct ys_usb_handle *handle,unsigned char *data,int count) { unsigned char *txbuf; int i,ret,actual_length;//,times,realsize; int totalsize,packetsize,packetnum,headersize,offset1,offset2; struct usb_driver_header header; #if CRC_ENABLE int crc_size; #endif // pthread_mutex_lock(&(handle->rwlock)); // pthread_mutex_lock(&(handle->lock)); headersize = sizeof(struct usb_driver_header); packetsize = MaxPacketSize - headersize; if(count%packetsize==0) packetnum = count/packetsize; else packetnum = count/packetsize + 1; totalsize = count+packetnum*headersize; txbuf = malloc(totalsize); if(txbuf==NULL){ ysprint("usb_write() malloc buffer failed!\n"); return -1; } offset1 = 0; offset2 = 0; header.length = packetnum; for(i=0;i<packetnum;i++){ header.num = i+1; header.size = (count-offset2)>packetsize? packetsize:(count-offset2) + sizeof(struct usb_driver_header); #if CRC_ENABLE crc_size = (count-offset2)>packetsize? packetsize:(count-offset2); header.crc = get_crc(data+offset2,crc_size); //ysprint("header.crc = %d,data[%d] = %d\n",header.crc,offset2,data[offset2]); #endif memcpy(txbuf+offset1,&header,sizeof(struct usb_driver_header)); offset1 += headersize; memcpy(txbuf+offset1,data+offset2,(count-offset2)>packetsize? packetsize:(count-offset2)); offset2 += packetsize; offset1 += packetsize; } #if 0 if(totalsize%MAX_BULK_LENGTH==0)times = totalsize/MAX_BULK_LENGTH; else times = totalsize/MAX_BULK_LENGTH + 1; offset1 = 0; for(i=0;i<times;i++){ if(i==(times-1)){ realsize = totalsize - MAX_BULK_LENGTH*i; ret = libusb_bulk_transfer(handle->libusb_handle,handle->Endpoint_out,txbuf+offset1,realsize,&actual_length,0); if(ret<0){ ysprint("USB write data failed,ret = %d,USB idProduct = %x\n",ret,handle->idproduct); }else{ actual_length = actual_length - packetnum*headersize; if(actual_length!=count){ ysprint("USB write count not equal actual length\n"); ret = -1; } } }else { realsize = MAX_BULK_LENGTH; ret = libusb_bulk_transfer(handle->libusb_handle,handle->Endpoint_out,txbuf+offset1,realsize,&actual_length,0); if(ret<0){ ysprint("USB write data failed,ret = %d,USB idProduct = %x\n",ret,handle->idproduct); }else{ actual_length = actual_length - packetnum*headersize; if(actual_length!=count){ ysprint("USB write count not equal actual length\n"); ret = -1; } } } offset1 += realsize; } #else ret = libusb_bulk_transfer(handle->libusb_handle,handle->Endpoint_out,txbuf,totalsize,&actual_length,0); if (ret < 0) { ysprint("USB write data failed,ret = %d,USB idProduct = %x\n",ret,handle->idproduct); } else { actual_length = actual_length - packetnum*headersize; if (actual_length != count) { ysprint("USB write count not equal actual length\n"); ret = -1; } } #endif if(txbuf!=NULL){ free(txbuf); txbuf = NULL; } // pthread_mutex_unlock(&(handle->lock)); // pthread_mutex_unlock(&(handle->rwlock)); return ret; }
//-------------------------------------------------------------------------------------------------------------------------- // 检查校验和(直接取累加和) // buf: 数据缓冲区指针 // len: 数据的长度 // 返回: 校验是否正确 bool CComAdjust::check_crc(const byte *buf, const int len) { byte check_sum = get_crc( buf+1, len-1 ); return (buf[0]==check_sum); }
uint32_t genfile_cache::convert_src2crc(const std::string &source, const std::string &options) { std::string source_options = source + options; return get_crc(source_options); }
/********************************************** 函数说明:USB读函数,读不到数据阻塞。成功返回读到 的字节数,失败返回-1。count是要读取的字节数,如果 count小于实际读到的字节,会内存溢出!不支持多线程 同时读,否则出现不可预料的错误。 **********************************************/ int usb_read(struct ys_usb_handle *handle, unsigned char *data, int count) { unsigned char *rxbuf = NULL; int ret,headersize,packetsize,offset,actual_length,size; struct usb_driver_header header; #if CRC_ENABLE unsigned char crc; #endif // pthread_mutex_lock(&(handle->rwlock)); headersize = sizeof(struct usb_driver_header); if (count >= MAX_BULK_LENGTH) packetsize = MAX_BULK_LENGTH; else packetsize = count; rxbuf = malloc(packetsize+headersize); if (rxbuf == NULL) { ysprint("usb_read() malloc buffer failed!\n"); return -1; } size = 0; offset = 0; actual_length = 0; while(1) { memset(rxbuf, 0x0, packetsize+ headersize); ret = libusb_bulk_transfer(handle->libusb_handle, handle->Endpoint_in, rxbuf, packetsize+headersize, &actual_length, 0); if (ret < 0) { if (ret != -7) ysprint("USB read data failed,ret = %d,USB idProduct = %x\n", ret, handle->idproduct); break; } else { header.num = rxbuf[0]; header.length = rxbuf[1]; header.type = rxbuf[2]; header.crc = rxbuf[3]; header.size = *(unsigned int *)(rxbuf+4); if (actual_length- header.size == 1) { //ysprint("why here!!!!!!!!!!, %d- %d\n", actual_length, header.size); actual_length = header.size; } if (header.num < header.length) { size += actual_length- headersize; if(offset+ actual_length- headersize > count) { ysprint("usb_read out of memory!\n"); ret = OUTOFMEM; break; } memcpy(data+ offset,rxbuf+ headersize,actual_length- headersize); #if CRC_ENABLE crc = get_crc(rxbuf+ headersize, actual_length- headersize); if (header.crc != crc) { ysprint("%s: %d %s: CRC error: subframe %d, nframes %d, header.size %d, header.crc %d, get crc = %d.\n", __FILE__, __LINE__, __FUNCTION__, header.num- 1, header.length, header.size, header.crc, crc); ret = CRCERROR; break; } #endif offset += actual_length-headersize; } else if (header.num == header.length) { size += actual_length-headersize; if (offset+ actual_length-headersize > count) { ysprint("usb_read out of memory!\n"); ret = OUTOFMEM; break; } memcpy(data+offset,rxbuf+headersize,actual_length-headersize); #if CRC_ENABLE crc = get_crc(rxbuf+ headersize, actual_length-headersize); if (header.crc != crc) { ysprint("%s: %d %s: CRC error: subframe %d, nframes %d, header.size %d, header.crc %d, get crc = %d.\n", __FILE__, __LINE__, __FUNCTION__, header.num- 1, header.length, header.size, header.crc, crc); ret = CRCERROR; break; } #endif offset += actual_length-headersize; break; } else { ysprint("usb_read the data error,header.num = %d, header.length = %d\n",header.num, header.length); ret = SEQERROR; break; } } } // pthread_mutex_unlock(&(handle->rwlock)); if (ret == 0) ret = size; if (rxbuf) { free(rxbuf); rxbuf = NULL; } return ret; }