TlsContext *tlsInit(void) { TlsContext *context; //Allocate a memory buffer to hold the TLS context context = osMemAlloc(sizeof(TlsContext)); //Failed to allocate memory if(!context) return NULL; //Clear TLS context memset(context, 0, sizeof(TlsContext)); //Reference to the underlying socket #if (TLS_BSD_SOCKET_SUPPORT == ENABLED) context->socket = SOCKET_ERROR; #else context->socket = NULL; #endif //Default operation mode context->entity = TLS_CONNECTION_END_CLIENT; //Default TLS version context->version = TLS_MIN_VERSION; //Default client authentication mode context->clientAuthMode = TLS_CLIENT_AUTH_NONE; //Initialize multiple precision integers dhInitParameters(&context->dhParameters); rsaInitPublicKey(&context->peerRsaPublicKey); dsaInitPublicKey(&context->peerDsaPublicKey); //Allocate send and receive buffers context->txBuffer = osMemAlloc(TLS_TX_BUFFER_SIZE); context->rxBuffer = osMemAlloc(TLS_RX_BUFFER_SIZE); //Failed to allocate memory? if(!context->txBuffer || !context->rxBuffer) { //Free previously allocated memory osMemFree(context->txBuffer); osMemFree(context->rxBuffer); osMemFree(context); //Report an error return NULL; } //Clear send and receive buffers memset(context->txBuffer, 0, TLS_TX_BUFFER_SIZE); memset(context->rxBuffer, 0, TLS_RX_BUFFER_SIZE); //Return a handle to the freshly created TLS context return context; }
error_t udpEchoStart(void) { error_t error; EchoServiceContext *context; OsTask *task; //Debug message TRACE_INFO("Starting UDP echo service...\r\n"); //Allocate a memory block to hold the context context = osMemAlloc(sizeof(EchoServiceContext)); //Failed to allocate memory? if(!context) return ERROR_OUT_OF_MEMORY; //Start of exception handling block do { //Open a UDP socket context->socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_PROTOCOL_UDP); //Failed to open socket? if(!context->socket) { //Report an error error = ERROR_OPEN_FAILED; //Exit immediately break; } //The server listens for incoming datagrams on port 7 error = socketBind(context->socket, &IP_ADDR_ANY, ECHO_PORT); //Unable to bind the socket to the desired port? if(error) break; //Create a task to handle incoming datagrams task = osTaskCreate("UDP Echo", udpEchoTask, context, ECHO_SERVICE_STACK_SIZE, ECHO_SERVICE_PRIORITY); //Unable to create the task? if(task == OS_INVALID_HANDLE) { //Report an error to the calling function error = ERROR_OUT_OF_RESOURCES; break; } //End of exception handling block } while(0); //Any error to report? if(error) { //Clean up side effects... socketClose(context->socket); osMemFree(context); } //Return status code return error; }
void memPoolFree(void *p) { //Use fixed-size blocks allocation? #if (MEM_POOL_SUPPORT == ENABLED) uint_t i; //Acquire exclusive access to the memory pool osMutexAcquire(memPoolMutex); //Loop through allocation table for(i = 0; i < MEM_POOL_BUFFER_COUNT; i++) { if(memPool[i] == p) { //Mark the current block as free memPoolAllocTable[i] = FALSE; //Exit immediately break; } } //Release exclusive access to the memory pool osMutexRelease(memPoolMutex); #else //Release memory block osMemFree(p); #endif }
void tlsFree(TlsContext *context) { //Invalid TLS context? if(context == NULL) return; //Properly close the TLS session by sending a close notify tlsShutdown(context); //Release server name osMemFree(context->serverName); //Free multiple precision integers dhFreeParameters(&context->dhParameters); rsaFreePublicKey(&context->peerRsaPublicKey); dsaFreePublicKey(&context->peerDsaPublicKey); //Release send buffer memset(context->txBuffer, 0, TLS_TX_BUFFER_SIZE); osMemFree(context->txBuffer); //Release receive buffer memset(context->rxBuffer, 0, TLS_RX_BUFFER_SIZE); osMemFree(context->rxBuffer); //Release resources used to compute handshake message hash osMemFree(context->handshakeMd5Context); osMemFree(context->handshakeSha1Context); osMemFree(context->handshakeHashContext); //Release the write encryption context if(context->writeCipherContext) { //Clear context contents, then release memory memset(context->writeCipherContext, 0, context->cipherAlgo->contextSize); osMemFree(context->writeCipherContext); } //Release the read encryption context if(context->readCipherContext) { //Clear context contents, then release memory memset(context->readCipherContext, 0, context->cipherAlgo->contextSize); osMemFree(context->readCipherContext); } //Clear the TLS context before freeing memory memset(context, 0, sizeof(TlsContext)); osMemFree(context); }
error_t sha224Compute(const void *data, size_t length, uint8_t *digest) { //Allocate a memory buffer to hold the SHA-224 context Sha224Context *context = osMemAlloc(sizeof(Sha224Context)); //Failed to allocate memory? if(!context) return ERROR_OUT_OF_MEMORY; //Initialize the SHA-224 context sha224Init(context); //Digest the message sha224Update(context, data, length); //Finalize the SHA-224 message digest sha224Final(context, digest); //Free previously allocated memory osMemFree(context); //Successful processing return NO_ERROR; }
FILE *fopen(const char_t *filename, const char_t *mode) { error_t error; DirEntry dirEntry; FsFile *file; error = resSearchFile(filename, &dirEntry); if(error) return NULL; file = osMemAlloc(sizeof(FsFile)); if(!file) return NULL; error = resOpenFile(file, &dirEntry, MODE_BINARY); if(error) { osMemFree(file); return NULL; } return (FILE *) file; }
void tcpEchoListenerTask(void *param) { error_t error; uint16_t clientPort; IpAddr clientIpAddr; Socket *serverSocket; Socket *clientSocket; EchoServiceContext *context; OsTask *task; //Point to the listening socket serverSocket = (Socket *) param; //Main loop while(1) { //Accept an incoming connection clientSocket = socketAccept(serverSocket, &clientIpAddr, &clientPort); //Check whether a valid connection request has been received if(!clientSocket) continue; //Debug message TRACE_INFO("Echo service: connection established with client %s port %u\r\n", ipAddrToString(&clientIpAddr, NULL), clientPort); //The socket operates in non-blocking mode error = socketSetTimeout(clientSocket, 0); //Any error to report? if(error) { //Close socket socketClose(clientSocket); //Wait for an incoming connection attempt continue; } //Allocate resources for the new connection context = osMemAlloc(sizeof(EchoServiceContext)); //Failed to allocate memory? if(!context) { //Close socket socketClose(clientSocket); //Wait for an incoming connection attempt continue; } //Record the handle of the newly created socket context->socket = clientSocket; //Create a task to service the current connection task = osTaskCreate("TCP Echo Connection", tcpEchoConnectionTask, context, ECHO_SERVICE_STACK_SIZE, ECHO_SERVICE_PRIORITY); //Did we encounter an error? if(task == OS_INVALID_HANDLE) { //Close socket socketClose(clientSocket); //Release resources osMemFree(context); } } }
void tcpChargenConnectionTask(void *param) { error_t error; //size_t i; size_t n; //size_t offset; size_t byteCount; systime_t startTime; systime_t duration; ChargenServiceContext *context; //Get a pointer to the context context = (ChargenServiceContext *) param; //Get current time startTime = osGetTickCount(); //Initialize counters byteCount = 0; //offset = 0; //Once a connection is established a stream of data is sent out //the connection (and any data received is thrown away). This //continues until the calling user terminates the connection while(1) { //Format output data /*for(i = 0; i < CHARGEN_BUFFER_SIZE; i += 95) { //Calculate the length of the current line n = min(CHARGEN_BUFFER_SIZE - i, 95); //Copy character pattern memcpy(context->buffer + i, pattern + offset, n); } //Update offset offset += CHARGEN_BUFFER_SIZE + 95 - i; //Wrap around if necessary if(offset >= 95) offset = 0;*/ //Send data error = socketSend(context->socket, context->buffer, CHARGEN_BUFFER_SIZE, &n, 0); //Any error to report? if(error) break; //Total number of bytes sent byteCount += n; } //Graceful shutdown socketShutdown(context->socket, SOCKET_SD_BOTH); //Compute total duration duration = osGetTickCount() - startTime; //Avoid division by zero... if(!duration) duration = 1; //Debug message TRACE_INFO("Chargen service: %" PRIuSIZE " bytes " "sent in %" PRIu32 " ms (%" PRIu32 " kBps, %" PRIu32 " kbps)\r\n", byteCount, duration, byteCount / duration, (byteCount * 8) / duration); //Close socket socketClose(context->socket); //Release previously allocated memory osMemFree(context); //Kill ourselves osTaskDelete(NULL); }
error_t dnsResolve(NetInterface *interface, const char_t *name, IpAddr *ipAddr) { error_t error; uint_t i; size_t length; uint16_t identifier; IpAddr serverIpAddr; Socket *socket; DnsHeader *dnsMessage; //Debug message TRACE_INFO("Trying to resolve %s...\r\n", name); //Use default network interface? if(!interface) interface = tcpIpStackGetDefaultInterface(); //Allocate a memory buffer to hold DNS messages dnsMessage = memPoolAlloc(DNS_MESSAGE_MAX_SIZE); //Failed to allocate memory? if(!dnsMessage) return ERROR_OUT_OF_MEMORY; //Open a UDP socket socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_PROTOCOL_UDP); //Failed to open socket? if(!socket) { //Free previously allocated memory osMemFree(dnsMessage); //Return status code return ERROR_OPEN_FAILED; } #if (IPV4_SUPPORT == ENABLED) //IP address of the DNS server serverIpAddr.length = sizeof(Ipv4Addr); serverIpAddr.ipv4Addr = interface->ipv4Config.dnsServer[0]; #elif (IPV6_SUPPORT == ENABLED) //IP address of the DNS server serverIpAddr.length = sizeof(Ipv6Addr); serverIpAddr.ipv6Addr = interface->ipv6Config.dnsServer[0]; #endif //Associate the socket with the relevant interface error = socketBindToInterface(socket, interface); //Any error to report? if(error) { //Free previously allocated memory osMemFree(dnsMessage); //Close socket socketClose(socket); //Return status code return error; } //Connect the newly created socket to the primary DNS server error = socketConnect(socket, &serverIpAddr, DNS_PORT); //Failed to connect? if(error) { //Free previously allocated memory osMemFree(dnsMessage); //Close socket socketClose(socket); //Return status code return error; } //An identifier is used by the client to match replies //with corresponding requests identifier = rand(); //Try to retransmit the DNS message if the previous query timed out for(i = 0; i < DNS_MAX_RETRIES; i++) { //Send DNS query message error = dnsSendQuery(socket, dnsMessage, identifier, name); //Failed to send message ? if(error) break; //Adjust receive timeout error = socketSetTimeout(socket, DNS_REQUEST_TIMEOUT); //Any error to report? if(error) break; //Wait for the server response error = socketReceive(socket, dnsMessage, DNS_MESSAGE_MAX_SIZE, &length, 0); //Any response from the specified DNS server? if(!error) { //Parse DNS response error = dnsParseResponse(dnsMessage, length, identifier, ipAddr); //DNS response successfully decoded? if(!error) break; } } //The maximum number of retransmissions has been reached? if(i >= DNS_MAX_RETRIES) error = ERROR_TIMEOUT; //Free previously allocated memory osMemFree(dnsMessage); //Close socket socketClose(socket); //Debug message if(!error) { //Name resolution succeeds TRACE_INFO("Host name resolved to %s...\r\n", ipAddrToString(ipAddr, NULL)); } else { //Report an error TRACE_ERROR("DNS resolution failed!\r\n"); } //Return status code return error; }
error_t dnsParseResponse(DnsHeader *dnsMessage, size_t length, uint16_t identifier, IpAddr *ipAddr) { char_t *name; uint_t i; size_t pos; Ipv4Addr ipv4Addr; DnsQuestion *dnsQuestion; DnsResourceRecord *dnsResourceRecord; //Clear host address memset(ipAddr, 0, sizeof(IpAddr)); //Ensure the DNS header is valid if(length < sizeof(DnsHeader)) return ERROR_INVALID_HEADER; //Compare identifier against expected one if(dnsMessage->identifier != identifier) return ERROR_WRONG_IDENTIFIER; //Check message type if(!(dnsMessage->flags & DNS_FLAG_QR)) return ERROR_INVALID_HEADER; //Make sure recursion is available if(!(dnsMessage->flags & DNS_FLAG_RA)) return ERROR_INVALID_HEADER; //Check return code if(dnsMessage->flags & DNS_RCODE_MASK) return ERROR_FAILURE; //Debug message TRACE_DEBUG("DNS response message received (%u bytes)...\r\n", length); //Allocate memory buffer to hold the decoded name name = memPoolAlloc(DNS_NAME_MAX_SIZE); //Failed to allocate memory if(!name) return ERROR_OUT_OF_MEMORY; //Debug message TRACE_DEBUG("%u questions found...\r\n", ntohs(dnsMessage->questionCount)); //Point to the first question pos = sizeof(DnsHeader); //Parse questions for(i = 0; i < ntohs(dnsMessage->questionCount); i++) { //Decode domain name pos = dnsDecodeName(dnsMessage, length, pos, name); //Name decoding failed? if(!pos) { //Free previously allocated memory osMemFree(name); //Report an error return ERROR_INVALID_NAME; } //Point to the associated resource record dnsQuestion = DNS_GET_RESOURCE_RECORD(dnsMessage, pos); //Debug message TRACE_DEBUG(" name = %s\r\n", name); TRACE_DEBUG(" queryType = %u\r\n", ntohs(dnsQuestion->queryType)); TRACE_DEBUG(" queryClass = %u\r\n", ntohs(dnsQuestion->queryClass)); //Point to the next question pos += sizeof(DnsQuestion); } //Debug message TRACE_INFO("%u answer RRs found...\r\n", ntohs(dnsMessage->answerRecordCount)); //Parse answer resource records for(i = 0; i < ntohs(dnsMessage->answerRecordCount); i++) { //Decode domain name pos = dnsDecodeName(dnsMessage, length, pos, name); //Name decoding failed? if(!pos) { //Free previously allocated memory osMemFree(name); //Report an error return ERROR_INVALID_NAME; } //Point to the associated resource record dnsResourceRecord = DNS_GET_RESOURCE_RECORD(dnsMessage, pos); //Debug message TRACE_DEBUG(" name = %s\r\n", name); TRACE_DEBUG(" type = %u\r\n", ntohs(dnsResourceRecord->type)); TRACE_DEBUG(" class = %u\r\n", ntohs(dnsResourceRecord->class)); TRACE_DEBUG(" ttl = %u\r\n", ntohl(dnsResourceRecord->timeToLive)); TRACE_DEBUG(" dataLength = %u\r\n", ntohs(dnsResourceRecord->dataLength)); //Check the type of the resource record switch(ntohs(dnsResourceRecord->type)) { //IPv4 address record found? case DNS_RR_TYPE_A: //Verify the length of the data field if(ntohs(dnsResourceRecord->dataLength) != sizeof(Ipv4Addr)) break; //Copy the IP address ipv4CopyAddr(&ipv4Addr, dnsResourceRecord->data); //Save the first IP address found in resource records if(!ipAddr->length) { ipAddr->length = sizeof(Ipv4Addr); ipAddr->ipv4Addr = ipv4Addr; } //Debug message TRACE_DEBUG(" data = %s\r\n", ipv4AddrToString(ipv4Addr, NULL)); break; //IPv6 address record found? /*case DNS_RR_TYPE_AAAA: //Verify the length of the data field if(ntohs(dnsResourceRecord->dataLength) != sizeof(Ipv6Addr)) break; //Copy the IP address //ipv4CopyAddr(&ipv4Addr, dnsResourceRecord->data); //Save the first IP address found in resource records if(!ipAddr->length) { ipAddr->length = sizeof(Ipv6Addr); ipv6CopyAddr(&ipAddr->ipv6Addr, dnsResourceRecord->data); } //Debug message //TRACE_DEBUG(" data = %s\r\n", ipv4AddrToString(ipv4Addr, NULL)); break;*/ //Name server record found? case DNS_RR_TYPE_NS: //Canonical name record found? case DNS_RR_TYPE_CNAME: //Pointer record? case DNS_RR_TYPE_PTR: //Decode the canonical name dnsDecodeName(dnsMessage, length, pos + sizeof(DnsResourceRecord), name); //Debug message TRACE_DEBUG(" data = %s\r\n", name); break; //Unknown record default: break; } //Point to the next resource record pos += sizeof(DnsResourceRecord) + ntohs(dnsResourceRecord->dataLength); } //Debug message TRACE_INFO("%u authority RRs found...\r\n", ntohs(dnsMessage->authorityRecordCount)); TRACE_INFO("%u additional RRs found...\r\n", ntohs(dnsMessage->additionalRecordCount)); //Free previously allocated memory osMemFree(name); //DNS response successfully decoded return NO_ERROR; }
int_t fclose(FILE * stream) { osMemFree(stream); //The stream is successfully closed return 0; }
error_t pemReadDhParameters(const char_t *input, size_t length, DhParameters *params) { error_t error; size_t i; size_t j; int_t k; char_t *buffer; const uint8_t *data; Asn1Tag tag; //Check parameters if(input == NULL && length != 0) return ERROR_INVALID_PARAMETER; if(params == NULL) return ERROR_INVALID_PARAMETER; //Search for the beginning tag k = pemSearchTag(input, length, "-----BEGIN DH PARAMETERS-----", 29); //Failed to find the specified tag? if(k < 0) return ERROR_INVALID_SYNTAX; //Advance the pointer over the tag input += k + 29; length -= k + 29; //Search for the end tag k = pemSearchTag(input, length, "-----END DH PARAMETERS-----", 27); //Invalid PEM file? if(k <= 0) return ERROR_INVALID_SYNTAX; //Length of the PEM structure length = k; //Allocate a memory buffer to hold the decoded data buffer = osMemAlloc(length); //Failed to allocate memory? if(!buffer) return ERROR_OUT_OF_MEMORY; //Copy the contents of the PEM structure memcpy(buffer, input, length); //Remove carriage returns and line feeds for(i = 0, j = 0; i < length; i++) { if(buffer[i] != '\r' && buffer[i] != '\n') buffer[j++] = buffer[i]; } //Start of exception handling block do { //The PEM file is Base64 encoded... error = base64Decode(buffer, j, buffer, &length); //Failed to decode the file? if(error) break; //Point to the resulting ASN.1 structure data = (uint8_t *) buffer; //Display ASN.1 structure error = asn1DumpObject(data, length, 0); //Any error to report? if(error) break; //The Diffie-Hellman parameters are encapsulated within a sequence error = asn1ReadTag(data, length, &tag); //Failed to decode ASN.1 tag? if(error) break; //Enforce encoding, type and class error = asn1CheckTag(&tag, TRUE, ASN1_CLASS_UNIVERSAL, ASN1_TYPE_SEQUENCE); //The tag does not match the criteria? if(error) break; //Point to the first field of the sequence data = tag.value; length = tag.length; //Read the prime modulus error = asn1ReadTag(data, length, &tag); //Failed to decode ASN.1 tag? if(error) break; //Enforce encoding, type and class error = asn1CheckTag(&tag, FALSE, ASN1_CLASS_UNIVERSAL, ASN1_TYPE_INTEGER); //The tag does not match the criteria? if(error) break; //Convert the prime modulus to a multiple precision integer error = mpiReadRaw(¶ms->p, tag.value, tag.length); //Any error to report? if(error) break; //Point to the next field data += tag.totalLength; length -= tag.totalLength; //Read the generator error = asn1ReadTag(data, length, &tag); //Failed to decode ASN.1 tag? if(error) break; //Enforce encoding, type and class error = asn1CheckTag(&tag, FALSE, ASN1_CLASS_UNIVERSAL, ASN1_TYPE_INTEGER); //The tag does not match the criteria? if(error) break; //Convert the generator to a multiple precision integer error = mpiReadRaw(¶ms->g, tag.value, tag.length); //Any error to report? if(error) break; //Debug message TRACE_DEBUG("Diffie-Hellman parameters:\r\n"); TRACE_DEBUG(" Prime modulus:\r\n"); TRACE_DEBUG_MPI(" ", ¶ms->p); TRACE_DEBUG(" Generator:\r\n"); TRACE_DEBUG_MPI(" ", ¶ms->g); //End of exception handling block } while(0); //Release previously allocated memory osMemFree(buffer); //Clean up side effects if necessary if(error) dhFreeParameters(params); //Return status code return error; }
UINT32 myXdcfCopyDisk(UINT32 ui32dstDirPos) { UINT8 filename[20]; UINT32 temp,temp1; UINT32 err = SUCCESS; UINT32 ui32FileIdx; UINT32 ui32FileCnt; UINT32 ui32DirCnt; UINT32 ui32DirIdx; UINT32 ui32DirPos; UINT32 ui32DirPos2; UINT32 ui32FileSize; UINT32 *pui32SavePage = NULL; SINT32 fd,fd2; xdcfAttrElm_t xdcfFileAttr; xdcfAttrElm_t xdcfDirAttr; xdcfCurDirPosGet(&ui32DirPos); xdcfFileCountGet(&ui32FileCnt); #if C_FILE_DEBUG printf("fine counter=%d,%d ",ui32DirPos,ui32FileCnt); #endif if(!ui32FileCnt) goto copyFileOver; pui32SavePage = osMemAlloc(C_READ_SECTION); if(!pui32SavePage) { #if C_FILE_DEBUG printf("alloc 100k fail "); #endif goto copyFileOver; } ui32FileIdx = 1; for(;ui32FileIdx<=ui32FileCnt;ui32FileIdx++) { xdcfActiveDevIdSet(DRIVE_NAND); xdcfCurDirByPosSet(ui32DirPos); xdcfCurFileByPosSet(ui32FileIdx); xdcfCurFileAttrGet(&xdcfFileAttr); myReadFilename(filename, xdcfFileAttr.name); fd = vfsOpen(xdcfFileAttr.name, O_BINARY, S_IREAD); ui32FileSize = vfsFileSizeGet(fd); xdcfActiveDevIdSet(DRIVE_SD); xdcfCurDirByPosSet(ui32dstDirPos); #if C_FILE_DEBUG printf("file %s=%d ",filename,ui32FileSize); #endif fd2 = vfsOpen(filename, O_CREATE, 0); while(ui32FileSize) { if(ui32FileSize>=C_READ_SECTION) temp = C_READ_SECTION; else temp = ui32FileSize; ui32FileSize -= temp; xdcfActiveDevIdSet(DRIVE_NAND); vfsRead(fd, pui32SavePage, temp); xdcfActiveDevIdSet(DRIVE_SD); temp1 = vfsWrite(fd2, pui32SavePage, temp); if(temp!=temp1) err |= FAIL; } vfsClose(fd); vfsClose(fd2); } copyFileOver: #if 0 #if C_FILE_DEBUG printf("dircnt=%d ",ui32DirCnt); #endif if(!ui32DirCnt) goto copyDirOver; ui32DirIdx = 1; xdcfActiveDevIdSet(DRIVE_NAND); err |= xdcfCurDirByPosSet(ui32DirPos); vfsCurrDirReset(); #if C_FILE_DEBUG printf("dir0=%s ",vfsGetCurrDirName()); #endif xdcfDirCountGet(&ui32DirCnt); xdcfCurDirAttrGet(&xdcfDirAttr); #if C_FILE_DEBUG printf("dir=%s ",xdcfDirAttr.name); #endif while((err|=xdcfCurDirByDirectSet(xDCF_MOVE_NEXT))==SUCCESS) { xdcfCurDirAttrGet(&xdcfDirAttr); #if C_FILE_DEBUG printf("dir=%s ",xdcfDirAttr.name); #endif } #if 0 for(;ui32DirIdx<=ui32DirCnt;ui32DirIdx++) { xdcfActiveDevIdSet(DRIVE_SD); err |= xdcfCurDirByPosSet(ui32dstDirPos); vfsMkdir(xdcfDirAttr.name); vfsChdir(xdcfDirAttr.name); xdcfCurDirPosGet(&ui32DirPos2); xdcfActiveDevIdSet(DRIVE_NAND); err |= xdcfCurDirByPosSet(ui32DirPos); myXdcfCopyDisk(ui32DirPos2); } #endif copyDirOver: #endif if(pui32SavePage) { osMemFree(pui32SavePage); pui32SavePage = NULL; } xdcfActiveDevIdSet(DRIVE_NAND); xdcfCurDirByPosSet(ui32DirPos); return err; }
void myGetSingleDayDL(UINT32 pos, UINT32 *ui32Data) { UINT8 *pStr; UINT8 *ui32Addr[32]; UINT32 j,k,len; UINT32 err = SUCCESS; UINT32 filesize; SINT32 i32DLfd; xdcfAttrElm_t xdcfFileAttr1; ui32Data[0] = 0; if((pos==0)||(ui8TimeFlag==0)) return; xdcfCurFileByPosSet(pos); err = xdcfCurFileAttrGet(&xdcfFileAttr1); i32DLfd = vfsOpen(xdcfFileAttr1.name, O_RDWR, 0); if(!i32DLfd) { #if C_FILE_DEBUG printf("open %s error ",xdcfFileAttr1.name); #endif return; } else { filesize = xdcfFileSizeGet(i32DLfd); j = strlen(ui8DLHeader1)+7+sizeof(ui8DLHeader2); for(k=0;k<C_DL_HEADER_3_LEN;k++) { j += strlen(ui8DLHeader3[k]); } j += 2; #if C_FILE_DEBUG printf("file header=%d ",j); #endif if(filesize<=j) return; len = filesize-j; pStr = osMemAlloc(len); if(!pStr) { #if C_FILE_DEBUG printf("alloc memory fail=%d ",len+1); #endif return; } vfsLseek(i32DLfd, j, SEEK_SET); vfsRead(i32DLfd, pStr, len); pStr[len] = '\0'; k = 0; while(k<len) { for(j=1;(pStr[k]!='\n')&&(pStr[k]!='\0');k++) { /*if(pStr[k]==',') { pStr[k] = '\0'; ui32Addr[j++] = &pStr[k+1]; }*/ } if(pStr[k]=='\0') return; k++; ui32Data[0]++; } vfsClose(i32DLfd); osMemFree(pStr); } }
error_t ping(NetInterface *interface, const IpAddr *ipAddr, time_t timeout, time_t *rtt) { error_t error; uint_t i; size_t length; uint16_t identifier; uint16_t sequenceNumber; time_t startTime; time_t roundTripTime; Socket *socket; IcmpEchoMessage *message; //Debug message TRACE_INFO("Pinging %s with 64 bytes of data...\r\n", ipAddrToString(ipAddr, NULL)); //Length of the complete ICMP message including header and data length = sizeof(IcmpEchoMessage) + PING_DATA_SIZE; //Allocate memory buffer to hold an ICMP message message = osMemAlloc(length); //Failed to allocate memory? if(!message) return ERROR_OUT_OF_MEMORY; //Identifier field is used to help matching requests and replies identifier = rand(); //Sequence Number field is increment each time an Echo Request is sent sequenceNumber = osAtomicInc16(&pingSequenceNumber); //Format ICMP Echo Request message message->type = ICMP_TYPE_ECHO_REQUEST; message->code = 0; message->checksum = 0; message->identifier = identifier; message->sequenceNumber = sequenceNumber; //Copy data for(i = 0; i < PING_DATA_SIZE; i++) message->data[i] = i; #if (IPV4_SUPPORT == ENABLED) //Target address is an IPv4 address? if(ipAddr->length == sizeof(Ipv4Addr)) { Ipv4Addr srcIpAddr; //Select the source IPv4 address and the relevant network //interface to use when pinging the specified host error = ipv4SelectSourceAddr(&interface, ipAddr->ipv4Addr, &srcIpAddr); //Any error to report? if(error) { //Free previously allocated memory osMemFree(message); //Return the corresponding error code return error; } //ICMP Echo Request message message->type = ICMP_TYPE_ECHO_REQUEST; //Message checksum calculation message->checksum = ipCalcChecksum(message, length); //Open a raw socket socket = socketOpen(SOCKET_TYPE_RAW, SOCKET_PROTOCOL_ICMP); } else #endif #if (IPV6_SUPPORT == ENABLED) //Target address is an IPv6 address? if(ipAddr->length == sizeof(Ipv6Addr)) { Ipv6PseudoHeader pseudoHeader; //Select the source IPv6 address and the relevant network //interface to use when pinging the specified host error = ipv6SelectSourceAddr(&interface, &ipAddr->ipv6Addr, &pseudoHeader.srcAddr); //Any error to report? if(error) { //Free previously allocated memory osMemFree(message); //Return the corresponding error code return error; } //ICMPv6 Echo Request message message->type = ICMPV6_TYPE_ECHO_REQUEST; //Format IPv6 pseudo header pseudoHeader.destAddr = ipAddr->ipv6Addr; pseudoHeader.length = htonl(length); pseudoHeader.reserved = 0; pseudoHeader.nextHeader = IPV6_ICMPV6_HEADER; //Message checksum calculation message->checksum = ipCalcUpperLayerChecksum( &pseudoHeader, sizeof(Ipv6PseudoHeader), message, length); //Open a raw socket socket = socketOpen(SOCKET_TYPE_RAW, SOCKET_PROTOCOL_ICMPV6); } else #endif //Target address is not valid? { //Free previously allocated memory osMemFree(message); //Report an error return ERROR_INVALID_ADDRESS; } //Failed to open socket? if(!socket) { //Free previously allocated memory osMemFree(message); //Report an error return ERROR_OPEN_FAILED; } //Associate the newly created socket with the relevant interface error = socketBindToInterface(socket, interface); //Unable to bind the socket to the desired interface? if(error) { //Free previously allocated memory osMemFree(message); //Close socket socketClose(socket); //Return status code return error; } //Connect the socket to the target host error = socketConnect(socket, ipAddr, 0); //Any error to report? if(error) { //Free previously allocated memory osMemFree(message); //Close socket socketClose(socket); //Return status code return error; } //Send Echo Request message error = socketSend(socket, message, length, NULL, 0); //Failed to send message ? if(error) { //Free previously allocated memory osMemFree(message); //Close socket socketClose(socket); //Return status code return error; } //Save the time at which the request was sent startTime = osGetTickCount(); //Timeout value exceeded? while((osGetTickCount() - startTime) < timeout) { //Adjust receive timeout error = socketSetTimeout(socket, timeout); //Any error to report? if(error) break; //Wait for an incoming ICMP message error = socketReceive(socket, message, sizeof(IcmpEchoMessage) + PING_DATA_SIZE, &length, 0); //Any error to report? if(error) break; //Check message length if(length != (sizeof(IcmpEchoMessage) + PING_DATA_SIZE)) continue; //Verify message type if(ipAddr->length == sizeof(Ipv4Addr) && message->type != ICMP_TYPE_ECHO_REPLY) continue; if(ipAddr->length == sizeof(Ipv6Addr) && message->type != ICMPV6_TYPE_ECHO_REPLY) continue; //Response identifier matches request identifier? if(message->identifier != identifier) continue; //Make sure the sequence number is correct if(message->sequenceNumber != sequenceNumber) continue; //Loop through data field for(i = 0; i < PING_DATA_SIZE; i++) { //Compare received data against expected data if(message->data[i] != i) break; } //Valid Echo Reply message received? if(i == PING_DATA_SIZE) { //Calculate round-trip time roundTripTime = osGetTickCount() - startTime; //Debug message TRACE_INFO("Echo received (round-trip time = %ums)...\r\n", roundTripTime); //Free previously allocated memory osMemFree(message); //Close socket socketClose(socket); //Return round-trip time if(rtt) *rtt = roundTripTime; //No error to report return NO_ERROR; } } //Debug message TRACE_INFO("No echo received!\r\n"); //Free previously allocated memory osMemFree(message); //Close socket socketClose(socket); //No Echo Reply received from host... return ERROR_NO_RESPONSE; }
error_t icecastClientStart(IcecastClientContext *context, const IcecastClientSettings *settings) { error_t error; OsTask *task; //Debug message TRACE_INFO("Starting Icecast client...\r\n"); //Ensure the parameters are valid if(!context || !settings) return ERROR_INVALID_PARAMETER; //Clear the Icecast client context memset(context, 0, sizeof(IcecastClientContext)); //Save user settings context->settings = *settings; //Get the size of the circular buffer context->bufferSize = settings->bufferSize; //Start of exception handling block do { //Allocate a memory block to hold the circular buffer context->streamBuffer = osMemAlloc(context->bufferSize); //Failed to allocate memory? if(!context->streamBuffer) { //Report an error to the calling function error = ERROR_OUT_OF_MEMORY; break; } //Create mutex object to protect critical sections context->mutex = osMutexCreate(FALSE); //Failed to create mutex object? if(context->mutex == OS_INVALID_HANDLE) { //Report an error to the calling function error = ERROR_OUT_OF_RESOURCES; break; } //Create events to get notified when the buffer is writable/readable context->writeEvent = osEventCreate(FALSE, TRUE); context->readEvent = osEventCreate(FALSE, FALSE); //Failed to create event object? if(context->writeEvent == OS_INVALID_HANDLE || context->readEvent == OS_INVALID_HANDLE) { //Report an error to the calling function error = ERROR_OUT_OF_RESOURCES; break; } //Create the Icecast client task task = osTaskCreate("Icecast client", icecastClientTask, context, ICECAST_CLIENT_STACK_SIZE, ICECAST_CLIENT_PRIORITY); //Unable to create the task? if(task == OS_INVALID_HANDLE) { //Report an error to the calling function error = ERROR_OUT_OF_RESOURCES; break; } //Successful initialization error = NO_ERROR; //End of exception handling block } while(0); //Check whether an error occurred if(error) { //Clean up side effects... osMemFree(context->streamBuffer); osMutexClose(context->mutex); osEventClose(context->writeEvent); osEventClose(context->readEvent); } //Return status code return error; }
error_t httpServerUriNotFoundCallback(HttpConnection *connection) { error_t error; uint_t i; uint_t j; uint_t n; char_t *buffer; //Process data.xml file? if(!strcasecmp(connection->request.uri, "/data.xml")) { //Point to the scratch buffer buffer = connection->buffer + 384; //Format XML data n = sprintf(buffer, "<data>\r\n"); n += sprintf(buffer + n, " <ax>%d</ax>\r\n", 0); // fixme n += sprintf(buffer + n, " <ay>%d</ay>\r\n", 0); // fixme n += sprintf(buffer + n, " <az>%d</az>\r\n", 0); // fixme n += sprintf(buffer + n, " <adc>%u</adc>\r\n", 100); // fixme n += sprintf(buffer + n, " <joystick>%u</joystick>\r\n", 0); // fixme //End of XML data n += sprintf(buffer + n, "</data>\r\n"); //Format HTTP response header connection->response.version = connection->request.version; connection->response.statusCode = 200; connection->response.keepAlive = connection->request.keepAlive; connection->response.noCache = TRUE; connection->response.contentType = mimeGetType(".xml"); connection->response.chunkedEncoding = FALSE; connection->response.contentLength = n; //Send the header to the client error = httpWriteHeader(connection); //Any error to report? if(error) return error; //Send response body error = httpWriteStream(connection, buffer, n); //Any error to report? if(error) return error; //Properly close output stream error = httpCloseStream(connection); //Return status code return error; } //Process send_mail.xml file? else if(!strcasecmp(connection->request.uri, "/send_mail.xml")) { char *separator; char *property; char *value; char *p; SmtpAuthInfo authInfo; SmtpMail mail; SmtpMailAddr recipients[4]; //Initialize structures to zero memset(&authInfo, 0, sizeof(authInfo)); memset(&mail, 0, sizeof(mail)); memset(recipients, 0, sizeof(recipients)); //Set the relevant PRNG algorithm to be used authInfo.prngAlgo = YARROW_PRNG_ALGO; authInfo.prngContext = &yarrowContext; //Set email recipients mail.recipients = recipients; //Point to the scratch buffer buffer = connection->buffer; //Start of exception handling block do { //Process HTTP request body while(1) { //Read the HTTP request body until a ampersand is encountered error = httpReadStream(connection, buffer, HTTP_SERVER_BUFFER_SIZE - 1, &n, HTTP_FLAG_BREAK('&')); //End of stream detected? if(error) break; //Properly terminate the string with a NULL character buffer[n] = '\0'; //Remove the trailing ampersand if(n > 0 && buffer[n - 1] == '&') buffer[--n] = '\0'; //Decode the percent-encoded string for(i = 0, j = 0; i < n; i++, j++) { //Replace '+' characters with spaces if(buffer[i] == '+') { buffer[j] = ' '; } //Process percent-encoded characters else if(buffer[i] == '%' && (i + 2) < n) { buffer[i] = buffer[i + 1]; buffer[i + 1] = buffer[i + 2]; buffer[i + 2] = '\0'; buffer[j] = strtoul(buffer + i, NULL, 16); i += 2; } //Copy any other characters else { buffer[j] = buffer[i]; } } //Properly terminate the resulting string buffer[j] = '\0'; //Check whether a separator is present separator = strchr(buffer, '='); //Separator found? if(separator) { //Split the line *separator = '\0'; //Get property name and value property = strTrimWhitespace(buffer); value = strTrimWhitespace(separator + 1); //Check property name if(!strcasecmp(property, "server")) { //Save server name authInfo.serverName = strDuplicate(value); } else if(!strcasecmp(property, "port")) { //Save the server port to be used authInfo.serverPort = atoi(value); } else if(!strcasecmp(property, "userName")) { //Save user name authInfo.userName = strDuplicate(value); } else if(!strcasecmp(property, "password")) { //Save password authInfo.password = strDuplicate(value); } else if(!strcasecmp(property, "useTls")) { //Open a secure SSL/TLS session? authInfo.useTls = TRUE; } else if(!strcasecmp(property, "recipient")) { //Split the recipient address list value = strtok_r(value, ", ", &p); //Loop through the list while(value != NULL) { //Save recipient address recipients[mail.recipientCount].name = NULL; recipients[mail.recipientCount].addr = strDuplicate(value); recipients[mail.recipientCount].type = SMTP_RCPT_TYPE_TO; //Get the next item in the list value = strtok_r(NULL, ", ", &p); //Increment the number of recipients if(++mail.recipientCount >= arraysize(recipients)) break; } } else if(!strcasecmp(property, "from")) { //Save sender address mail.from.name = NULL; mail.from.addr = strDuplicate(value); } else if(!strcasecmp(property, "date")) { //Save current time mail.dateTime = strDuplicate(value); } else if(!strcasecmp(property, "subject")) { //Save mail subject mail.subject = strDuplicate(value); } else if(!strcasecmp(property, "body")) { //Save mail body mail.body = strDuplicate(value); } } } //Propagate exception if necessary if(error != ERROR_END_OF_STREAM) break; //Send mail error = smtpSendMail(&authInfo, &mail); //Point to the scratch buffer buffer = connection->buffer + 384; //Format XML data n = sprintf(buffer, "<data>\r\n <status>"); if(error == NO_ERROR) n += sprintf(buffer + n, "Mail successfully sent!\r\n"); else if(error == ERROR_NAME_RESOLUTION_FAILED) n += sprintf(buffer + n, "Cannot resolve SMTP server name!\r\n"); else if(error == ERROR_AUTHENTICATION_FAILED) n += sprintf(buffer + n, "Authentication failed!\r\n"); else if(error == ERROR_UNEXPECTED_RESPONSE) n += sprintf(buffer + n, "Unexpected response from SMTP server!\r\n"); else n += sprintf(buffer + n, "Failed to send mail (error %d)!\r\n", error); n += sprintf(buffer + n, "</status>\r\n</data>\r\n"); //Format HTTP response header connection->response.version = connection->request.version; connection->response.statusCode = 200; connection->response.keepAlive = connection->request.keepAlive; connection->response.noCache = TRUE; connection->response.contentType = mimeGetType(".xml"); connection->response.chunkedEncoding = FALSE; connection->response.contentLength = n; //Send the header to the client error = httpWriteHeader(connection); //Any error to report? if(error) break; //Send response body error = httpWriteStream(connection, buffer, n); //Any error to report? if(error) break; //Properly close output stream error = httpCloseStream(connection); //Any error to report? if(error) break; //End of exception handling block } while(0); //Free previously allocated memory osMemFree((void *) authInfo.serverName); osMemFree((void *) authInfo.userName); osMemFree((void *) authInfo.password); osMemFree((void *) recipients[0].addr); osMemFree((void *) mail.from.addr); osMemFree((void *) mail.dateTime); osMemFree((void *) mail.subject); osMemFree((void *) mail.body); //Return status code return error; } else { return ERROR_NOT_FOUND; } }
void tcpEchoConnectionTask(void *param) { error_t error; uint_t n; uint_t writeIndex; uint_t readIndex; uint_t bufferLength; uint_t rxByteCount; uint_t txByteCount; time_t startTime; time_t duration; SocketEventDesc eventDesc; EchoServiceContext *context; //Get a pointer to the context context = (EchoServiceContext *) param; //Get current time startTime = osGetTickCount(); //Initialize variables writeIndex = 0; readIndex = 0; bufferLength = 0; rxByteCount = 0; txByteCount = 0; //Main loop while(1) { //Buffer is empty? if(!bufferLength) { //Get notified when the socket is readable eventDesc.socket = context->socket; eventDesc.eventMask = SOCKET_EVENT_RX_READY; } //Buffer is not empty of full? else if(bufferLength < ECHO_BUFFER_SIZE) { //Get notified when the socket is readable or writable eventDesc.socket = context->socket; eventDesc.eventMask = SOCKET_EVENT_RX_READY | SOCKET_EVENT_TX_READY; } //Buffer is full? else { //Get notified when the socket is writable eventDesc.socket = context->socket; eventDesc.eventMask = SOCKET_EVENT_TX_READY; } //Wait for an event to be fired error = socketPoll(&eventDesc, 1, NULL, ECHO_TIMEOUT); //Timeout error or any other exception to report? if(error) break; //The socket is available for reading if(eventDesc.eventFlags & SOCKET_EVENT_RX_READY) { //Read as much data as possible n = min(ECHO_BUFFER_SIZE - writeIndex, ECHO_BUFFER_SIZE - bufferLength); //Read incoming data error = socketReceive(context->socket, context->buffer + writeIndex, n, &n, 0); //Any error to report? if(error) break; //Increment write index writeIndex += n; //Wrap around if necessary if(writeIndex >= ECHO_BUFFER_SIZE) writeIndex = 0; //Increment buffer length bufferLength += n; //Total number of bytes received rxByteCount += n; } //The socket is available for writing? if(eventDesc.eventFlags & SOCKET_EVENT_TX_READY) { //Write as much data as possible n = min(ECHO_BUFFER_SIZE - readIndex, bufferLength); //Send data back to the client error = socketSend(context->socket, context->buffer + readIndex, n, &n, 0); //Any error to report? if(error && error != ERROR_TIMEOUT) break; //Increment read index readIndex += n; //Wrap around if necessary if(readIndex >= ECHO_BUFFER_SIZE) readIndex = 0; //Update buffer length bufferLength -= n; //Total number of bytes sent txByteCount += n; } } //Adjust timeout value socketSetTimeout(context->socket, ECHO_TIMEOUT); //Graceful shutdown socketShutdown(context->socket, SOCKET_SD_BOTH); //Compute total duration duration = osGetTickCount() - startTime; //Debug message TRACE_INFO("Echo service: %u bytes received, %u bytes sent in %lu ms\r\n", rxByteCount, txByteCount, duration); //Close socket socketClose(context->socket); //Release previously allocated memory osMemFree(context); //Kill ourselves osTaskDelete(NULL); }
error_t tlsAddCertificate(TlsContext *context, const char_t *certChain, size_t certChainLength, const char_t *privateKey, size_t privateKeyLength) { error_t error; const char_t *p; size_t n; uint8_t *derCert; size_t derCertSize; size_t derCertLength; X509CertificateInfo *certInfo; TlsCertificateType certType; TlsSignatureAlgo certSignAlgo; TlsHashAlgo certHashAlgo; //Invalid TLS context? if(context == NULL) return ERROR_INVALID_PARAMETER; //Check parameters if(certChain == NULL || certChainLength == 0) return ERROR_INVALID_PARAMETER; if(privateKey == NULL || privateKeyLength == 0) return ERROR_INVALID_PARAMETER; //Make sure there is enough room to add the certificate if(context->numCerts >= TLS_MAX_CERTIFICATES) return ERROR_OUT_OF_RESOURCES; //Allocate a memory buffer to store X.509 certificate info certInfo = osMemAlloc(sizeof(X509CertificateInfo)); //Failed to allocate memory? if(!certInfo) return ERROR_OUT_OF_MEMORY; //Point to the beginning of the certificate chain p = certChain; n = certChainLength; //DER encoded certificate derCert = NULL; derCertSize = 0; derCertLength = 0; //Start of exception handling block do { //Decode end entity certificate error = pemReadCertificate(&p, &n, &derCert, &derCertSize, &derCertLength); //Any error to report? if(error) break; //Parse X.509 certificate error = x509ParseCertificate(derCert, derCertLength, certInfo); //Failed to parse the X.509 certificate? if(error) break; //Retrieve the signature algorithm that has been used to sign the certificate error = tlsGetCertificateType(certInfo, &certType, &certSignAlgo, &certHashAlgo); //The specified signature algorithm is not supported? if(error) break; //End of exception handling block } while(0); //Check whether the certificate is acceptable if(!error) { //Point to the structure that describes the certificate TlsCertDesc *cert = &context->certs[context->numCerts]; //Save the certificate chain and the corresponding private key cert->certChain = certChain; cert->certChainLength = certChainLength; cert->privateKey = privateKey; cert->privateKeyLength = privateKeyLength; cert->type = certType; cert->signAlgo = certSignAlgo; cert->hashAlgo = certHashAlgo; //Update the number of certificate context->numCerts++; } //Release previously allocated memory osMemFree(derCert); osMemFree(certInfo); //Return status code return error; }
void pbEBookTextGet_O( ) { UINT8 *pui8EBookBuf ; UINT8 *pbuf; UINT8 ui8Buf[ EBOOK_PERPAGE_CHARNUM + 1 ]; //270个 UINT32 x1, y1 = 0; UINT32 ui32CurPageLenConter = 0; UINT8 *ui8ReadbufTemp; //hisIconDisp(); //hisTimeDisp(); ui8ReadbufTemp = osMemAlloc(512); pui8EBookBuf = ui8ReadbufTemp; osTimeDly(3); //osSchedLock(); vfsLseek(handle, *(pui32SavePage+ui32CurPageFlag), SEEK_SET); ui32ReadSize = vfsRead(handle, pui8EBookBuf, 512); /* Paul@2006/05/29 add start */ if (g_ui8LoadBookmark == 0) { //osSchedUnlock(); osTimeDly(3); //osTimeDly(50); osdBarDraw(0, 20, 320, 220, 0); } //printf("\n ui32ReadSize:%d",ui32ReadSize); for ( y1=0 ; y1< EBOOK_PERROW_CHARNUM; y1++ ) //EBOOK_PERROW_CHARNUM = 9 { pbuf = ui8Buf; for ( x1 = 0; x1< EBOOK_PERLINE_CHARNUM ; ) { if ( ui32CurPageLenConter + x1 >= ui32ReadSize ) { *pbuf = '\0'; ui32FileIsEnd = 1; break; } else if ( ui32CurPageLenConter + x1 >= ui32ReadSize - 1 ) { *pbuf++ = *pui8EBookBuf; *pbuf = '\0'; ui32FileIsEnd = 1; break; } if ( *pui8EBookBuf < 0x80 ) { if ( *pui8EBookBuf == 0x0d && *(pui8EBookBuf + 1) == 0x0a ) //回车 { *pbuf++ = '\0'; pui8EBookBuf += 2; x1 += 2; break; } else { *pbuf++ = *pui8EBookBuf++ ; x1++; //占用一个字符 } } else if ( *pui8EBookBuf >= 0x80 ) { //当最后个一字符为汉字且长度只足够一个 //英文字符时,不显示 if ( x1+2 > EBOOK_PERLINE_CHARNUM ) { *pbuf = '\0'; break; } *pbuf++ = *pui8EBookBuf++; *pbuf++ = *pui8EBookBuf++; x1 += 2; //占用两个字符 } } pbuf = ui8Buf; ui32CurPageLenConter += x1; if ( strlen( pbuf ) > 30 ) { memcpy(pbuf,ui8Buf, 30); pbuf[30] = '\0'; } if ( g_ui8LoadBookmark == 0) { osdStrDisp( 10, y1 * (20+2) + 20, UserFont10x20, 0xf0, pbuf ); // 显示当前行的数据 } if ( ui32FileIsEnd ) break ; } if ( g_ui8LoadBookmark == 0) { pbuf = ui8Buf; sio_psprintf(pbuf, "%12d", ui32CurPageFlag + 1); osdStrDisp(50, 220,UserFont10x20,0xd0, pbuf); } if ( ui32FileIsEnd ) { osMemFree(ui8ReadbufTemp); return; } *(pui32SavePage + ui32CurPageFlag + 1 ) = *( pui32SavePage + ui32CurPageFlag ) + ui32CurPageLenConter; osMemFree(ui8ReadbufTemp); }
error_t pemReadCertificate(const char_t **input, size_t *inputLength, uint8_t **output, size_t *outputSize, size_t *outputLength) { error_t error; size_t length; size_t i; size_t j; int_t k; //Check parameters if(input == NULL || inputLength == NULL) return ERROR_INVALID_PARAMETER; if(output == NULL || outputSize == NULL || outputLength == NULL) return ERROR_INVALID_PARAMETER; //Search for the beginning tag k = pemSearchTag(*input, *inputLength, "-----BEGIN CERTIFICATE-----", 27); //Failed to find the specified tag? if(k < 0) return ERROR_END_OF_FILE; //Advance the input pointer over the tag *input += k + 27; *inputLength -= k + 27; //Search for the end tag k = pemSearchTag(*input, *inputLength, "-----END CERTIFICATE-----", 25); //Invalid PEM file? if(k <= 0) return ERROR_INVALID_SYNTAX; //Length of the PEM structure length = k; //Increase buffer size? if(length > *outputSize) { //Release previously allocated buffer if necessary if(*output != NULL) { osMemFree(*output); *output = NULL; *outputSize = 0; } //Allocate a memory buffer to hold the decoded data *output = osMemAlloc(length); //Failed to allocate memory? if(*output == NULL) return ERROR_OUT_OF_MEMORY; //Record the size of the buffer *outputSize = length; } //Copy the contents of the PEM structure memcpy(*output, *input, length); //Advance the input pointer over the certificate *input += length + 25; *inputLength -= length + 25; //Remove carriage returns and line feeds for(i = 0, j = 0; i < length; i++) { if((*output)[i] != '\r' && (*output)[i] != '\n') (*output)[j++] = (*output)[i]; } //Start of exception handling block do { //The PEM file is Base64 encoded... error = base64Decode((char_t *) *output, j, *output, &length); //Failed to decode the file? if(error) break; //Display ASN.1 structure error = asn1DumpObject(*output, length, 0); //Any error to report? if(error) break; //End of exception handling block } while(0); //Clean up side effects if(error) { //Release previously allocated memory osMemFree(*output); *output = NULL; *outputSize = 0; } //Size of the decoded certificate *outputLength = length; //Return status code return error; }
void uiebook() { UINT32 key = UI_KEY_MODE_EBOOK; UINT8 ui8EBookEXPName[4] = "TXT" ; UINT8 ui8EBooKTempExp1[4]= "tmp"; UINT8 ui8EBookTempExp2[4]="emx"; UINT32 err; semApp = osEventFindByName("APP_SEM"); uiKeyMsgQ = osEventFindByName("UI_KEY"); pbDispStart = 1; ui32DirIdx = 0; ui32FileIdx = 0; while ( ( uiState & UI_MODE_MASK ) ==UI_MODE_EBOOK) { hisIconDisp(); hisTimeDisp(); if (ui32NextState != uiState) { break; } switch(key) { case UI_KEY_DIR_UP: if( ui8DispType == PB_DISP_FOUR ) { if(ui32FileIdx >1) ui32FileIdx --; else ui32FileIdx = ui32FileCnt; pbEBookRefresh(); } else if ( ui8DispType == PB_DISP_ONE ) { pbEBookPrePage();//上一页 } break; case UI_KEY_DIR_DOWN: if( ui8DispType == PB_DISP_FOUR ) { if(ui32FileIdx < ui32FileCnt) ui32FileIdx ++; else ui32FileIdx = 1; pbEBookRefresh(); } else if (ui8DispType == PB_DISP_ONE) { pbEBookNextPage ();//下一页 } break; case UI_KEY_ACCIDENT: osTimeDly(20); if (pui8ReadBuf) { osMemFree (pui8ReadBuf); pui8ReadBuf = NULL; } if ( pui32SavePage ) { osMemFree (pui32SavePage); pui32SavePage = NULL; } if (handle) { vfsClose(handle); handle = 0; } if (ui8DispType == PB_DISP_ONE) { ui8DispType = PB_DISP_FOUR; ui8EBookReadNow = 0; pbEBookRefresh(); //fqdao_modify for bug 23 06.4.29 osQuePost(uiKeyMsgQ, &keyButton[UI_KEY_ACCIDENT]); } break; case UI_KEY_FUNC_B: if( ui8DispType == PB_DISP_FOUR ) //fqdao_add 06.5.16 { buttonAudio(1) ; paEBookMenuFunc(); } break ; case UI_KEY_DIR_LEFT: break; case UI_KEY_DIR_RIGHT: break; /* case UI_KEY_FUNC_ZOOMIN: break ; case UI_KEY_FUNC_ZOOMOUT: break ; */ case UI_KEY_FUNC_MENU: if( ui8DispType == PB_DISP_FOUR ) { if ( pui8ReadBuf ) { osMemFree( pui8ReadBuf ); pui8ReadBuf = NULL; } if ( pui32SavePage ) { osMemFree( pui32SavePage ); pui32SavePage = NULL; } if ( handle ) { vfsClose(handle); handle = 0; } sub_menu_acc = 0; // UI_OSQFlush(uiKeyMsgQ); menuReturn(UI_MAINMENU, 0); osTimeDly(40); return; break; // UI_OSQFlush(uiKeyMsgQ); } else if ( ui8DispType == PB_DISP_ONE ) { /* Paul@2006/05/29 add start */ IsSaveBookmark(); /* Paul@2006/05/29 add end */ #if 1 ui8DispType = PB_DISP_FOUR; if ( pui8ReadBuf ) { osMemFree(pui8ReadBuf); pui8ReadBuf = NULL; } if ( pui32SavePage ) { osMemFree( pui32SavePage ); pui32SavePage = NULL; } ui8EBookReadNow = 0; if ( handle ) { vfsClose(handle); handle = 0; } //UI_OSQFlush(uiKeyMsgQ); pbInit(); osdClearScreen(0); //fqdao_add 06.5.19 pbEBookShow(EBOOK_DRAW_BG ,0 ); pbEBookRefresh(); #endif } break ; // case UI_KEY_FUNC_MODE: // break; case UI_KEY_FUNC_OK: if (ui32FileCnt != 0 && ui8DispType == PB_DISP_FOUR ) { if(pui32SavePage==NULL) { pui32SavePage = osMemAlloc(4096); if ( !pui32SavePage ) { break; } } handle = vfsOpen( xdcfFileAttr.name, O_RDONLY, S_IREAD); if ( !handle ) { break; } ui32FileSize= vfsFileSizeGet(handle); if ( ui32FileSize == 0 ) { osdStrDisp(160, 60, UserFont10x20, 0xd0, GetBookString(EmptyFile)); osTimeDly(100); //vfsClose(handle); break; } #if 0 if ( ui32FileSize < 1024*400 ) { pui8ReadBuf = osMemAlloc( ui32FileSize ); if ( pui8ReadBuf == NULL ) { osMemFree(pui32SavePage); vfsClose(handle); break; } ui32ReadSize = vfsRead(handle, pui8ReadBuf, ui32FileSize ); } else { pui8ReadBuf = osMemAlloc( 1024*400 );/*最大400k*/ if ( pui8ReadBuf == NULL ) { osMemFree(pui32SavePage); vfsClose(handle); break; } ui32ReadSize = vfsRead(handle, pui8ReadBuf, 1024*400); } #endif ui8EBookReadNow = 1; //vfsClose(handle); ui8DispType = PB_DISP_ONE; *pui32SavePage = 0; /*第一页指向的0(开始位置)*/ ui32FileIsEnd = 0; ui32CurPageFlag = 0; ui32PrePageFlag = 0; /* Paul@2006/05/29 add start */ CheckCurBookmark(); /* Paul@2006/05/29 add end */ osdClearScreen(0); pbEBookRefresh(); osTimeDly(50); } break; // case UI_KEY_FUNC_DISP: // break; case UI_KEY_MODE_EBOOK: if ( ui8FirstInEBook ) { xdcfFileTypeAdd(ui8EBooKTempExp1); // 128 xdcfFileTypeAdd(ui8EBookTempExp2); //256 xdcfFileTypeAdd(ui8EBookEXPName);//512 相当于 1<<9 ( xDCF_FILETYPE_RESERVE2) ui8FirstInEBook = 0; } osTaskSuspend(osTaskFindByName("AAA")); sysgMemDispAddrGet(&ui32gPB); if ( pui32SavePage ) { osMemFree( pui32SavePage ); pui32SavePage = NULL; } if ( pui8ReadBuf ) { osMemFree(pui8ReadBuf); pui8ReadBuf = NULL; } //添加目录名 xdcfInit(imageDirNameStr, imageRootNameStr, xDCF_CONFIG_KEY_MIN | xDCF_CONFIG_SORT_IDX/* | xDCF_CONFIG_DCF_ONLY*/); xdcfCurRootDirSet(otherRootNameStr); xdcfFilterSet( ui32FileFilter ); //ui32FileFilter = xDCF_FILETYPE_RESERVE2; hwWait(0,100); xdcfDirCountGet(&ui32DirCnt); xdcfCurDirAttrGet(&xdcfDirAttr); xdcfFileCountGet(&ui32FileCnt); ui32FileIdx = 1; if(ui32FileCnt == 0) { ui32FileIdx = 0; } ui8DispType = PB_DISP_FOUR ; pbInit(); pbEBookShow(EBOOK_DRAW_BG ,0 ); pbEBookRefresh(); break; default: break; } EBookkeyGet(&key); } if ( pui8ReadBuf ) { osMemFree(pui8ReadBuf); pui8ReadBuf = NULL; } if ( pui32SavePage ) { osMemFree( pui32SavePage ); pui32SavePage = NULL; } if ( handle ) { vfsClose(handle); handle = 0; } uiState = ui32NextState; }