Beispiel #1
0
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;
}
Beispiel #2
0
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;
}
Beispiel #3
0
error_t tlsSetServerName(TlsContext *context, const char_t *serverName)
{
   size_t i;
   size_t length;

   //Invalid parameters?
   if(context == NULL || serverName == NULL)
      return ERROR_INVALID_PARAMETER;

   //Retrieve the length of the server name
   length = strlen(serverName);

   //Allocate a memory block to hold the hostname
   context->serverName = osMemAlloc(length + 1);
   //Failed to allocate memory?
   if(!context->serverName) return ERROR_OUT_OF_MEMORY;

   //Convert the hostname into lowercase
   for(i = 0; i < length; i++)
      context->serverName[i] = tolower((uint8_t) serverName[i]);

   //Properly terminate the string with a NULL character
   context->serverName[length] = '\0';

   //Successful processing
   return NO_ERROR;
}
Beispiel #4
0
void *memPoolAlloc(size_t size)
{
#if (MEM_POOL_SUPPORT == ENABLED)
   uint_t i;
#endif

   //Pointer to the allocated memory block
   void *p = NULL;

   //Debug message
   TRACE_DEBUG("Allocating %" PRIuSIZE " bytes...\r\n", size);

//Use fixed-size blocks allocation?
#if (MEM_POOL_SUPPORT == ENABLED)
   //Acquire exclusive access to the memory pool
   osMutexAcquire(memPoolMutex);

   //Enforce block size
   if(size <= MEM_POOL_BUFFER_SIZE)
   {
      //Loop through allocation table
      for(i = 0; i < MEM_POOL_BUFFER_COUNT; i++)
      {
         //Check whether the current block is free
         if(!memPoolAllocTable[i])
         {
            //Mark the current entry as used
            memPoolAllocTable[i] = TRUE;
            //Point to the corresponding memory block
            p = memPool[i];

            //Update statistics
            memPoolCurrentUsage++;
            //Maximum number of buffers that have been allocated so far
            memPoolMaxUsage = max(memPoolCurrentUsage, memPoolMaxUsage);

            //Exit immediately
            break;
         }
      }
   }

   //Release exclusive access to the memory pool
   osMutexRelease(memPoolMutex);
#else
   //Allocate a memory block
   p = osMemAlloc(size);
#endif

   //Failed to allocate memory?
   if(!p)
   {
      //Debug message
      TRACE_WARNING("Memory allocation failed!\r\n");
   }

   //Return a pointer to the allocated memory block
   return p;
}
Beispiel #5
0
char_t *strDuplicate(const char_t *s)
{
    uint_t n;
    char_t *p;

    //Calculate the length occupied by the input string
    n = strlen(s) + 1;

    //Allocate memory to hold the new string
    p = osMemAlloc(n);
    //Failed to allocate memory?
    if(!p) return NULL;

    //Make a copy of the input string
    memcpy(p, s, n);

    //Return a pointer to the newly created string
    return p;
}
Beispiel #6
0
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;
}
Beispiel #7
0
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;
}
Beispiel #8
0
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);
      }
   }
}
Beispiel #9
0
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;
}
Beispiel #10
0
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;
}
Beispiel #11
0
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;

}
Beispiel #12
0
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;
}
Beispiel #14
0
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);

}
Beispiel #15
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(&params->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(&params->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("    ", &params->p);
      TRACE_DEBUG("  Generator:\r\n");
      TRACE_DEBUG_MPI("    ", &params->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;
}
Beispiel #16
0
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;
}
Beispiel #17
0
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);
	}
}