/**
 * \function 	UDPlistensendPort
 * \brief    	使用UDP协议实现广播侦听远程配置工具,并主动连接将相机IP地址告知
 * \			默认作为服务端,Port = 4502;主动连接平台时,作为客户端。
 * \
**/	
void UDPlistensendPort()
{
	SOCKET	sockUDPsendListen,sockTCPsendIP;
	int		clilen,len;
	int     label;
	struct	sockaddr_in sin,connaddr, clientaddr; //保存客户的地址信息
	struct  sockaddr pcliaddr;
	ConversationHead replySem;

	//为当前任务配置运行环境
	fdOpenSession( TaskSelf() );

	//创建侦听套接字socket对象
	sockUDPsendListen = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);//创建服务器监听socket,UDP协议
	if( sockUDPsendListen == INVALID_SOCKET )
	{
		Roseek_Reset();//如果创建侦听对象失败,重启相机
	}
	bzero( &sin, sizeof(struct sockaddr_in) );
	sin.sin_family	= AF_INET; 
	sin.sin_addr.s_addr = INADDR_ANY;//自动获取本机地址
	sin.sin_len	= sizeof( sin );
	sin.sin_port= htons( UDPPORT );//指明连接服务器的端口号
	//sockUDPsendListen绑定
	if ( bind( sockUDPsendListen, (PSA) &sin, sizeof(sin) ) < 0 )
	{
		Roseek_Reset();//如果绑定失败,重启相机
	}

	//迭代接受控制消息
	while(1)
	{
		label = 10; 
	    clilen = sizeof(struct sockaddr);		
		//开始接收数据
		bTextRecev=recvfrom(sockUDPsendListen, (char *)(&replySem), sizeof(ConversationHead), 0, (PSA)&pcliaddr,&clilen);			
		if( bTextRecev < sizeof(ConversationHead) )
		{
			continue;
		}
		//存储配置工具的IP
		g_ConfigSetaddr= pcliaddr;	
					
		//作为客户端,创建TCP协议连接远程平台,端口4502,告知相机的IP
		sockTCPsendIP = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);//创建客户端socket.TCP协议
		if( sockTCPsendIP == INVALID_SOCKET )
		{
		    Roseek_Reset();//如果创建侦听对象失败,重启相机
	    }
		bzero( &connaddr,sizeof(struct sockaddr_in));
		connaddr.sin_family = AF_INET;
		connaddr.sin_addr.s_addr = INADDR_ANY;
		connaddr.sin_len = sizeof( connaddr );
		connaddr.sin_port = htons(0);
		if (bind(sockTCPsendIP, (PSA) &connaddr,sizeof(connaddr)))
		{
			Roseek_Reset();//如果绑定失败,重启相机
		} 
		bzero(&clientaddr, sizeof(struct sockaddr_in));
		clientaddr.sin_family = AF_INET;
		clientaddr.sin_addr = ((struct sockaddr_in*) &pcliaddr)->sin_addr;
		clientaddr.sin_len = sizeof( clientaddr );
		clientaddr.sin_port = htons(UDPPORT);		
		if(connect( sockTCPsendIP, (PSA)&clientaddr, clientaddr.sin_len)<0)
		{
			bTextConnect = 1;
			++bTextCount;
			continue;
		}
		else
		{
			bTextConnect = 0;
			if(replySem.command==UDPCON)
			{
				//发送信息1
				replySem.command = BROADCAST1;
				replySem.bufsize = DEVICETYPE;//设备类型参数
		      	len=send( sockTCPsendIP,&replySem, sizeof(replySem), 0 );
		      	//发送信息2
		      	replySem.command = UDPSETTIME;
		      	replySem.bufsize = label;
		      	len=send( sockTCPsendIP,&replySem, sizeof(replySem), 0);
		      	fdClose(sockTCPsendIP);
				if(len<0)
				{
					continue;
				}
			}
		}			

	}//迭代循环

}
static void daemon()
{
    int                i,closeSock;
    struct sockaddr_in sin1;
    SOCKET             tsock;
    CHILD              *pc;

    // Enter our lock
    SemPend( hDSem, SEM_FOREVER );

    for(;;)
    {
        //
        // Create any socket that needs to be created
        //
        for( i=0; i<DAEMON_MAXRECORD; i++ )
        {
            if( drec[i].Type && drec[i].s == INVALID_SOCKET )
            {
                // Create UDP or TCP as needed
                if( drec[i].Type == SOCK_DGRAM )
                    drec[i].s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
                else
                    drec[i].s = socket(AF_INET, drec[i].Type, IPPROTO_TCP);

                // If the socket was created, bind it
                if( drec[i].s != INVALID_SOCKET )
                {
                    // Bind to the specified Server port
                    bzero( &sin1, sizeof(struct sockaddr_in) );
                    sin1.sin_family      = AF_INET;
                    sin1.sin_len         = sizeof( sin1 );
                    sin1.sin_addr.s_addr = drec[i].LocalAddress;
                    sin1.sin_port        = htons(drec[i].LocalPort);

                    if( bind( drec[i].s,(struct sockaddr *)&sin1, sizeof(sin1) ) < 0 )
                    {
                        fdClose( drec[i].s );
                        drec[i].s = INVALID_SOCKET;
                    }
                }

                // If the socket is bound and TCP, start listening
                if( drec[i].s != INVALID_SOCKET && drec[i].Type != SOCK_DGRAM )
                {
                    if( listen( drec[i].s, drec[i].MaxSpawn ) < 0 )
                    {
                        fdClose( drec[i].s );
                        drec[i].s = INVALID_SOCKET;
                    }
                }
            }

            // Update the fdPoll array
            pollitem[i].fd = drec[i].s;
            if( drec[i].Type && drec[i].TasksSpawned < drec[i].MaxSpawn )
                pollitem[i].eventsRequested = POLLIN;
            else
                pollitem[i].eventsRequested = 0;
        }

        // Leave our lock
        SemPost( hDSem );

        // Poll with a timeout of 10 second - to try and catch
        // synchronization error
        if( fdPoll( pollitem, DAEMON_MAXRECORD, 10000 ) == SOCKET_ERROR )
            break;

        // Enter our lock
        SemPend( hDSem, SEM_FOREVER );

        //
        // Spawn tasks for any active sockets
        //
        for( i=0; i<DAEMON_MAXRECORD; i++ )
        {
            // If no poll results or the drec has been freed, skip it
            if( !pollitem[i].eventsDetected || !drec[i].Type )
                continue;

            // If the socket is invalid, close it
            if( pollitem[i].eventsDetected & POLLNVAL )
            {
                fdClose( drec[i].s);
                drec[i].s = INVALID_SOCKET;
                continue;
            }

            if( pollitem[i].eventsDetected & POLLIN )
            {
                if( drec[i].Type == SOCK_DGRAM )
                {
                    tsock = drec[i].s;
                    closeSock = 0;
                }
                else
                {
                    tsock = accept( drec[i].s, 0, 0 );
                    closeSock = 1;
                }

                if( tsock != INVALID_SOCKET )
                {
                    // Create a record to track this task
                    pc = mmAlloc( sizeof(CHILD) );
                    if( !pc )
                        goto spawnComplete;

                    // Create the task
                    pc->hTask = TaskCreate( dchild, "dchild",
                                            drec[i].Priority, drec[i].StackSize,
                                            (UINT32)&drec[i], (UINT32)pc, 0);
                    if( !pc->hTask )
                    {
                        mmFree( pc );
                        goto spawnComplete;
                    }

                    // Open a socket session for the child task
                    fdOpenSession( pc->hTask );

                    // Fill in the rest of the child record
                    pc->closeSock = closeSock;
                    pc->s = tsock;

                    // Now we won't close the socket here
                    closeSock = 0;

                    // Link this record onto the DREC
                    drec[i].TasksSpawned++;
                    pc->pPrev = 0;
                    pc->pNext = drec[i].pC;
                    drec[i].pC = pc;
                    if( pc->pNext )
                        pc->pNext->pPrev = pc;

spawnComplete:
                    // If there was an error, we may need to close the socket
                    if( closeSock )
                        fdClose( tsock );
                }
            }
        }
    }

    TaskExit();
}
Exemple #3
0
 // int NtTftpSend()
//
// Send a file using TFTP
//
// Return Conditions:
//
// In the following cases, FileSize is set to the actual file size:
//
//      1 - If file was sucessfully transferred
//      0 - ??
//      -1 - failed
//
// In the following cases, FileSize is set to the actual number of
// bytes copied.
//
//     <0 - Error
//        TFTPERROR_ERRORCODE: TFTP server error code. The error code
//          is written to pErrorCode, and an error message is
//          written to FileBuffer. The length of the error message
//          is written to FileSize.
//
int NtTftpSendLocal( UINT32 TftpIP, char *szFileName, char *FileBuffer,
                UINT32 *FileSize, UINT16 *pErrorCode )
{
    TFTP *pTftp;
    int rc;          // Return Code

    // Quick parameter validation
    if( !szFileName || !FileSize || (*FileSize != 0 && !FileBuffer) )
        return( TFTPERROR_BADPARAM );

    // Malloc Parameter Structure
    if( !(pTftp = mmAlloc( sizeof(TFTP) )) )
        return( TFTPERROR_RESOURCES );

    // Initialize parameters to "NULL"
    bzero( pTftp, sizeof(TFTP) );
    pTftp->Sock = INVALID_SOCKET;

    // Malloc Packet Data Buffer
    if( !(pTftp->PacketBuffer = mmAlloc( DATA_SIZE )) )
    {
        rc = TFTPERROR_RESOURCES;
        goto ABORT2;
    }

    // store IP in network byte order
    pTftp->PeerAddress = TftpIP;

    // Setup initial socket
    rc = tftpSocketSetup( pTftp );
    if( rc < 0 )
        goto ABORT2;

    //  Socket now registered and available for use. Get the data
    pTftp->szFileName  = szFileName;
    pTftp->Buffer      = FileBuffer;
    pTftp->BufferSize  = *FileSize;   // Do not read more than can fit in file
	pTftp->BufferUsed  = *FileSize;

    // PUT the requested file
    rc = tftpPutFile( pTftp );
    if( rc < 0 )
    {
        // ERROR CONDITION

        // Set the "FileSize" to the actual number of bytes copied
        //*FileSize = pTftp->BufferUsed;

        // If the ErrorCode pointer is valid, copy it
        if( pErrorCode )
            *pErrorCode = pTftp->ErrorCode;
    }
    else
    {
        // SUCCESS CONDITION

        // Set the "FileSize" to the file size (regardless of bytes copied)
        //*FileSize = pTftp->FileSize;
    }

ABORT2:
    if( pTftp->Sock != INVALID_SOCKET )
        fdClose( pTftp->Sock );
    if( pTftp->PacketBuffer )
        mmFree( pTftp->PacketBuffer );
    mmFree( pTftp );

    return(rc);
}
Exemple #4
0
void nullsrv()
{


    SOCKET   stcpactive = INVALID_SOCKET;
    struct   sockaddr_in sin1;
    struct   timeval timeout;           // Timeout struct for select
    int      size;
    int      cnt;
    char     *pBuf;
    HANDLE   hBuffer;

    //gpioEnableGlobalInterrupt();
    // Allocate the file environment for this task
    fdOpenSession(TaskSelf());


    TaskSleep(15000);
    platform_write("Raw Eth Task Started ... \n");
    // Create the main TCP listen socket
    platform_write("creating main TCP listen socket\n");

    int k=0;
        int n=0;
       IMG_STORE_REQST_TYP a;


            int *data;
            UInt32 time1,time2;
           for(;;)
           {
        	   	   //time1=Clock_getTicks();
        	   	   a.fps=acquire_data();
        	   	   a.number=min((int)a.fps*sizeof(int),PULSE_SAMPLE*sizeof(int));
        	   	   //time2=Clock_getTicks();
        	   	   ///platform_write("time taken for acquire data is %lu \n",(unsigned long)(time2-time1));
        	   	   //time1=Clock_getTicks();
                   for(k=0;k<2;k++)
                   {
                    if(k==0)
                    data=&data_bufferA[0];
                    else
                    data=&data_bufferB[0];
                   //WWdis_data();
                       stcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                       if( stcp == INVALID_SOCKET )
                       {
                           int ret=fdError();
                           goto leave;

                       }


        timeout.tv_sec  = 30;
        timeout.tv_usec = 0;
        setsockopt( stcp, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof( timeout ) );
        setsockopt( stcp, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof( timeout ) );
        //timeout.tv_sec  = 3;
        //int opt = 1;
        //setsockopt( stcp, SOL_SOCKET, SO_BLOCKING , &opt, sizeof( opt ) );

        platform_write("created main TCP client socket\n");
        // Set Port = 1001, leaving IP address = Any
        bzero( &sin1, sizeof(struct sockaddr_in) );
        sin1.sin_family = AF_INET;
        sin1.sin_addr.s_addr =inet_addr(PCStaticIP);
        sin1.sin_port   = htons(7000);
        sin1.sin_len    = sizeof( sin1 );




        platform_write("LLL %d \n",(sin1.sin_addr.s_addr));
        //fcntl(stcp, F_SETFL, O_NONBLOCK);





              //while(1)

              if( connect(stcp, (struct sockaddr *) &sin1, sizeof(sin1)) < 0)
              {
            	  if (fdError() == EINPROGRESS)
            	  {
            		  	  	  	 fd_set wrsd;
            		             struct timeval tv;

            		             FD_ZERO(&wrsd);
            		             FD_SET(stcp, &wrsd);
            		             tv.tv_sec = 2;
            		             tv.tv_usec = 0;
            		             int ret = fdSelect((int)stcp, 0, &wrsd, 0, &tv );
            		             if(ret>0)
            		             {
            		            	 int err, lenErr;
            		            	  lenErr = sizeof(err);
            		            	  ret = getsockopt(stcp, SOL_SOCKET, SO_ERROR, &err, &lenErr);
            		            	  if(ret==0 && err==0)
            		            	  {
            		            		  platform_write("connection completed");
            		            		  break;
            		            	  }
            		            	  else
            		            	  {
            		            		  platform_write("Attempting to connect again");
            		            		  continue;
            		            	  }
            		             }

            	  }

              }

          platform_write("completed connect \n");
         a.hydrophone=k;
         n=0;
            n = send(stcp,&a,sizeof(a),0);
              if (n < 0)
              {
                  perror("ERROR writing to socket");
                  break;
              }


              platform_write("writing hydrophone %d,bytes %d\n",k,a.number);

                n=0;
                int c=0;
                //platform_write("writing %s  \n",data);
                do
                {
                n = send(stcp,data,a.number-c,0);
                //platform_write("writing %d bytes \n",n);
                  if (n < 0)
                  {
                      perror("ERROR writing to socket");
                      break;
                  }
                  c=c+n;
                  data=data+n;
                }while(c<a.number);
                if (n < 0)
                	break;
                //free(orig);
                int status;
                HANDLE hbuffer;
                n = recv(stcp, &status, sizeof(status),0);

                if(status==0)
                {
                    platform_write("Client request success\n");
                }
                else
                {
                    platform_write("Client request error");
                    continue;
                }
                if( stcp != INVALID_SOCKET )
                fdClose(stcp);


             }
                   if( stcp != INVALID_SOCKET )
                   {

						      shutdown(stcp,0);
						      fdClose(stcp);
                   }
                   //time2=Clock_getTicks();
                   platform_write("time taken for  data transfer is  %lu \n",(unsigned long)(time2-time1));
               //TaskSleep(5);fe
    }

leave:

    TaskSleep(5000);
    // We only get here on an error - close the sockets
  //  if( stcp != INVALID_SOCKET )
    //    fdClose( stcp );

    platform_write("NullSrv Fatal Error\n");

//    NetworkClose((HANDLE)TaskSelf());
    // This task is killed by the system - here, we block
    //TaskBlock( TaskSelf() );
}
bool Foam::ping
(
    const word& destName,
    const label destPort,
    const label timeOut
)
{
    char *serverAddress;
    struct in_addr *ptr;
    struct hostent *hostPtr;
    volatile int sockfd;
    struct sockaddr_in destAddr;      // will hold the destination addr
    u_int addr;

    if ((hostPtr = gethostbyname(destName.c_str())) == NULL)
    {
        FatalErrorIn
        (
            "Foam::ping(const word&, const label)"
        )   << "gethostbyname error " << h_errno << " for host " << destName
            << abort(FatalError);
    }

    // Get first of the SLL of addresses
    serverAddress = *(hostPtr->h_addr_list);
    ptr = reinterpret_cast<struct in_addr*>(serverAddress);
    addr = ptr->s_addr;

    // Allocate socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        FatalErrorIn
        (
            "Foam::ping(const word&, const label)"
        )   << "socket error"
            << abort(FatalError);
    }

    // Fill sockaddr_in structure with dest address and port
    memset (reinterpret_cast<char *>(&destAddr), '\0', sizeof(destAddr));
    destAddr.sin_family = AF_INET;
    destAddr.sin_port = htons(ushort(destPort));
    destAddr.sin_addr.s_addr = addr;


    timer myTimer(timeOut);

    if (timedOut(myTimer))
    {
        // Setjmp from timer jumps back to here
        fdClose(sockfd);
        return false;
    }

    if
    (
        connect
        (
            sockfd,
            reinterpret_cast<struct sockaddr*>(&destAddr),
            sizeof(struct sockaddr)
        ) != 0
    )
    {
        // Connection refused. Check if network was actually used or not.

        int connectErr = errno;

        fdClose(sockfd);

        if (connectErr == ECONNREFUSED)
        {
            return true;
        }
        //perror("connect");

        return false;
    }

    fdClose(sockfd);

    return true;
}
/*------------------------------------------------------------------------- */
int httpsClientProcess( SOCKET Sock, WOLFSSL *ssl)
{
    HTTPS_MSG *pMsg = 0;
    int      nMethod;
    int      rc = 0;
    int      length,i,realmidx;
    int      (*PostFunction)(WOLFSSL *, int, unsigned char *) = 0;
    int      fCGI = 0;
    int termstrSizeRemaining = sizeof(pMsg->termstr);
    int parseSizeRemaining   = sizeof(pMsg->parsestr);
    int requestSizeRemaining = sizeof(pMsg->RequestedFile);
    struct timeval to;
    struct linger  lgr;


    /* Init the socket parameters */

    lgr.l_onoff  = 1;
    lgr.l_linger = 5;
    rc = setsockopt((int)Sock, SOL_SOCKET, SO_LINGER, &lgr, sizeof( lgr ));
    if (rc < 0) {
        goto SHUTDOWN;
    }

    /* Configure our socket timeout to be 10 seconds */
    to.tv_sec  = 20;
    to.tv_usec = 0;
    rc = setsockopt( (int)Sock, SOL_SOCKET, SO_SNDTIMEO, &to, sizeof( to ) );
    if (rc < 0) {
        goto SHUTDOWN;
    }

    rc = setsockopt( (int)Sock, SOL_SOCKET, SO_RCVTIMEO, &to, sizeof( to ) );
    if (rc < 0) {
        goto SHUTDOWN;
    }

    /* Start the HTTP message processing */

    pMsg = mmAlloc( sizeof(HTTPS_MSG) );
    if( !pMsg )
        goto SHUTDOWN;

    /* Init the message record */
    pMsg->Sock              = Sock;
    pMsg->ssl               = ssl;
    pMsg->parsed            = 0;
    pMsg->unparsed          = 0;
    pMsg->flagreadall       = 0;
    pMsg->length            = 0;
    pMsg->PostContentLength = 0;
    pMsg->URIArgs           = 0;
    pMsg->username[0]       = 0;
    pMsg->password[0]       = 0;

    if (strlen(CRLF) < termstrSizeRemaining) {
        strcpy(pMsg->termstr,  CRLF );
        termstrSizeRemaining = termstrSizeRemaining - strlen(CRLF);
    }
    else {
        /* Error constructing message, return failure */
        goto SHUTDOWN;
    }

    if (strlen(CRLF) < termstrSizeRemaining) {
        strcat(pMsg->termstr,  CRLF );
        termstrSizeRemaining = termstrSizeRemaining - strlen(CRLF);
    }
    else {
        /* Error constructing message, return failure */
        goto SHUTDOWN;
    }

    if (strlen(SPACE) < parseSizeRemaining) {
        strcpy(pMsg->parsestr, SPACE);
        parseSizeRemaining = parseSizeRemaining - strlen(SPACE);
    }
    else {
        /* Error constructing message, return failure */
        goto SHUTDOWN;
    }

    /* Read the method */
    rc = httpsParseRecv( pMsg );
    if( rc<=0  )
    {
        https400(ssl);
        goto SHUTDOWN;
    }
    nMethod = httpsExtractTag( pMsg->request );

    /* Get URI */
    rc = httpsParseRecv( pMsg );
    if( rc<=0 )
    {
        https400(ssl);
        goto SHUTDOWN;
    }
    strcpy( pMsg->URI, pMsg->request );

    /* Setup for CRLF delimitor (CRLFCRLF is still terminator) */
    if (strlen(CRLF) < parseSizeRemaining) {
        strcpy(pMsg->parsestr, CRLF);
        parseSizeRemaining = parseSizeRemaining - strlen(CRLF);
    }
    else {
        /* Error constructing message, return failure */
        goto SHUTDOWN;
    }

    /* Scan all tags for tags we're interested in */
    for(i=0;;i=1)
    {
        int nTag;

        rc = httpsParseRecv( pMsg );
        if( rc < 0 )
        {
            https400(ssl);
            goto SHUTDOWN;
        }
        if( rc == 0 )
            break;
        /* A null tag after a tag is a CRLFCRLF */
        if( i && !pMsg->request[0] )
            break;

        /* Extract the tag */
        nTag = httpsExtractTag( pMsg->request );

        /* Process all the tag types we care about */
        if( nTag == TAG_CLEN )
            pMsg->PostContentLength = atoi(pMsg->request + 16);

        if( nTag == TAG_AUTH )
            httpsGetAuthParams( pMsg, (unsigned char *)pMsg->request + 21 );
    }

    /* Process the URI into RequestedFile */
    length = strlen(pMsg->URI);

    /* Scan URI for a '?' and terminate at that point */
    for(i=0;i<length;i++)
        if( pMsg->URI[i] == '?' )
        {
            pMsg->URI[i] = 0;
            pMsg->URIArgs = pMsg->URI + i + 1;
            break;
        }

    /* Set the new string length (if any) */
    length = i;

    /* Assume success from this point on */
    rc = 1;

    /* If URI terminates with a '/', then add index.html, UNLESS */
    /* length is 1, in which case replace '/' with index.html */
    /* If URI does not terminate with a '/', use it as is */
    /* Note: We always remove the leading '/' */
    if( !length || (length == 1 && pMsg->URI[0] == '/') ) {
        if (strlen(DEFAULT_NAME) < requestSizeRemaining) {
            strcpy(pMsg->RequestedFile, DEFAULT_NAME);
            requestSizeRemaining =
                    requestSizeRemaining - strlen(DEFAULT_NAME);
        }
        else {
            /* Error constructing message, return failure */
            goto SHUTDOWN;
        }
    }
    else {
        if (strlen(pMsg->URI + 1) < requestSizeRemaining) {
            strcpy(pMsg->RequestedFile, pMsg->URI + 1);
            requestSizeRemaining =
                    requestSizeRemaining - strlen(pMsg->URI + 1);

            if (pMsg->URI[length - 1] == '/') {
                if (strlen(DEFAULT_NAME) < requestSizeRemaining) {
                    strcat(pMsg->RequestedFile, DEFAULT_NAME);
                    requestSizeRemaining =
                            requestSizeRemaining - strlen(DEFAULT_NAME);
                }
                else {
                    /* Error constructing message, return failure */
                    goto SHUTDOWN;
                }
            }
        }
        else {
            /* Error constructing message, return failure */
            goto SHUTDOWN;
        }
    }

    /* Authenticate the request */
    i=efss_filecheck(pMsg->RequestedFile,pMsg->username,pMsg->password,&realmidx);

    /* Act on filecheck status code */
    if( i & EFS_FC_NOTFOUND )
    {
        https404(ssl);
        goto SHUTDOWN;
    }
    if( i & EFS_FC_AUTHFAILED )
    {
        httpsAuthenticationReq( ssl, realmidx );
        goto SHUTDOWN;
    }
    if( i & EFS_FC_NOTALLOWED )
    {
        https405(ssl);
        goto SHUTDOWN;
    }
    if( i & EFS_FC_EXECUTE )
    {
        fCGI = 1;
        PostFunction = (int(*)(WOLFSSL *, int, unsigned char *))
                                   efss_loadfunction(pMsg->RequestedFile);
    }

    /* Execute based on the method and fCGI flag */
    switch (nMethod)
    {
    case TAG_GET:
        if( !fCGI ) {
            httpsSendFullResponse( ssl, HTTP_OK, pMsg->RequestedFile );
        }
        else
        {
            if( !PostFunction ) {  	
                https404(ssl);   /* function does not exist */
            }
            else
            {
                /* Now call Post function using the "get" syntax */
                if( !PostFunction( ssl, 0, (unsigned char *)pMsg->URIArgs ) )
                {
                    rc = 0;
                    goto SHUTDOWN_postclose;
                }
            }
        }
        break;

    case TAG_POST:
        if( !fCGI )
            https405(ssl);   /* file is not a CGI */
        else if( !PostFunction )
            https404(ssl);   /* function does not exist */
        /* Now call Post function using "post" syntax */
        else if( !PostFunction( ssl, pMsg->PostContentLength,
                               (unsigned char *)pMsg->URIArgs ) )
        {
            rc = 0;
            goto SHUTDOWN_postclose;
        }
        break;

    default:
        https501( ssl );   /*  Not Implemented */
        break;
    }

SHUTDOWN:
#if 0
/* Close socket on error */
    if( rc <= 0 )
        fdClose( Sock );
#endif
SHUTDOWN_postclose:
    /* Free buffer if we allocated one */
    if( pMsg )
        mmFree( pMsg );

    if( rc < 0 )
        rc = 0;

    return( rc );
}
Exemple #7
0
void
start(void* v)
    {
    char enc_pass[64];
    char salt[MSS_SALT_SIZE + 1];
    char passwd_line[128];
    XString passwd_contents;
    pFile passwd_file;
    char buf[256];
    int len;
    int offset;
    int pos;
    int uname_len;
    int found_user;
    size_t found_len;
    char* nlptr;
    char* ptr;

	cxssInitialize();

	/** No file specified? **/
	if (!CXPASSWD.PasswdFile[0]) 
	    {
	    puts("no passwd file specified (use option -f).");
	    exit(1);
	    }
	
	/** User asked us to read password from stdin? **/
	if (CXPASSWD.ReadStdin)
	    {
	    fgets(CXPASSWD.Password, sizeof(CXPASSWD.Password), stdin);
	    if (strchr(CXPASSWD.Password, '\n'))
		{
		*strchr(CXPASSWD.Password, '\n') = '\0';
		}
	    }

	/** Now get username and/or password if not supplied on command line **/
	if (!CXPASSWD.UserName[0]) 
	    {
	    ptr = readline("Username: "******"Password: "******"could not generate random bytes for password salt.");
	    exit(1);
	    }

	/** Generate encrypted credential **/
	if (mssGenCred(salt, MSS_SALT_SIZE, CXPASSWD.Password, enc_pass, sizeof(enc_pass)) < 0)
	    {
	    puts("could not generate encrypted password.");
	    exit(1);
	    }

	/** Generate our password file line **/
	snprintf(passwd_line, sizeof(passwd_line), "%s:%s\n", CXPASSWD.UserName, enc_pass);

	/** Open the password file **/
	passwd_file = fdOpen(CXPASSWD.PasswdFile, O_RDWR | O_CREAT, 0600);
	if (!passwd_file)
	    {
	    puts("could not open passwd file.");
	    exit(1);
	    }

	/** Read it into the xstring **/
	xsInit(&passwd_contents);
	while((len = fdRead(passwd_file, buf, sizeof(buf), 0, 0)) > 0)
	    {
	    xsConcatenate(&passwd_contents, buf, len);
	    }
	fdClose(passwd_file, 0);
	
	/** Do we already have this user? **/
	uname_len = strlen(CXPASSWD.UserName);
	offset = 0;
	found_user = -1;
	while((pos = xsFind(&passwd_contents, CXPASSWD.UserName, uname_len, offset)) >= 0)
	    {
	    if ((pos == 0 || xsString(&passwd_contents)[pos-1] == '\n') && xsString(&passwd_contents)[pos+uname_len] == ':')
		{
		/** Found it **/
		found_user = pos;
		found_len = strlen(xsString(&passwd_contents)+pos);
		if ((nlptr = strchr(xsString(&passwd_contents)+pos, '\n')) != NULL)
		    found_len = (nlptr - (xsString(&passwd_contents)+pos)) + 1;
		break;
		}
	    offset = pos+1;
	    }

	/** Replace if found, otherwise add the new user **/
	if (found_user >= 0)
	    xsSubst(&passwd_contents, found_user, found_len, passwd_line, strlen(passwd_line));
	else
	    xsConcatenate(&passwd_contents, passwd_line, strlen(passwd_line));

	/** Rewrite the entire file **/
	passwd_file = fdOpen(CXPASSWD.PasswdFile, O_RDWR | O_CREAT | O_TRUNC, 0600);
	if (!passwd_file)
	    {
	    puts("could not open password file to write to it.");
	    exit(1);
	    }

	if (fdWrite(passwd_file, xsString(&passwd_contents), strlen(xsString(&passwd_contents)), 0, FD_U_SEEK | FD_U_PACKET) != strlen(xsString(&passwd_contents)))
	    {
	    puts("could not re-write new password file.");
	    exit(1);
	    }

	/** Close the file **/
	fdClose(passwd_file, 0);

    exit(0);
    }
/*
 *  ======== tcpHandler ========
 *  Creates new Task to handle new TCP connections.
 */
Void tcpHandler(UArg arg0, UArg arg1) {
	int sockfd;
	int ret;
	struct sockaddr_in servAddr;
	Error_Block eb;
	bool flag = true;
	bool internal_flag = true;
	int nbytes;
	char *buffer;
	char msg[] = "Hello from TM4C1294XL Connected Launchpad";
	WOLFSSL* ssl = (WOLFSSL *) arg0;

	fdOpenSession(TaskSelf());

	wolfSSL_Init();
	WOLFSSL_CTX* ctx = NULL;

	ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
	if (ctx == 0) {
		System_printf("tcpHandler: wolfSSL_CTX_new error.\n");
		exitApp(ctx);
	}

	if (wolfSSL_CTX_load_verify_buffer(ctx, ca_cert_der_2048,
			sizeof(ca_cert_der_2048) / sizeof(char), SSL_FILETYPE_ASN1)
			!= SSL_SUCCESS) {
		System_printf("tcpHandler: Error loading ca_cert_der_2048"
				" please check the wolfssl/certs_test.h file.\n");
		exitApp(ctx);
	}

	if (wolfSSL_CTX_use_certificate_buffer(ctx, client_cert_der_2048,
			sizeof(client_cert_der_2048) / sizeof(char), SSL_FILETYPE_ASN1)
			!= SSL_SUCCESS) {
		System_printf("tcpHandler: Error loading client_cert_der_2048,"
				" please check the wolfssl/certs_test.h file.\n");
		exitApp(ctx);
	}

	if (wolfSSL_CTX_use_PrivateKey_buffer(ctx, client_key_der_2048,
			sizeof(client_key_der_2048) / sizeof(char), SSL_FILETYPE_ASN1)
			!= SSL_SUCCESS) {
		System_printf("tcpHandler: Error loading client_key_der_2048,"
				" please check the wolfssl/certs_test.h file.\n");
		exitApp(ctx);
	}

	/* Init the Error_Block */
	Error_init(&eb);

	do {
		sockfd = socket(AF_INET, SOCK_STREAM, 0);
		if (sockfd < 0) {
			System_printf("tcpHandler: socket failed\n");
			Task_sleep(2000);
			continue;
		}

		memset((char *) &servAddr, 0, sizeof(servAddr));
		servAddr.sin_family = AF_INET;
		servAddr.sin_port = htons(TCPPORT);

		inet_aton(IP_ADDR, &servAddr.sin_addr);

		ret = connect(sockfd, (struct sockaddr *) &servAddr, sizeof(servAddr));

		if (ret < 0) {
			fdClose((SOCKET) sockfd);
			Task_sleep(2000);
			continue;
		}
	} while (ret != 0);

	if ((ssl = wolfSSL_new(ctx)) == NULL) {
		System_printf("tcpHandler: wolfSSL_new error.\n");
		exitApp(ctx);
	}

	wolfSSL_set_fd(ssl, sockfd);

	ret = wolfSSL_connect(ssl);

	/* Delete "TOP_LINE" and "END_LINE" for debugging. */

	/* TOP_LINE

	 System_printf("looked for: %d.\n", SSL_SUCCESS);
	 System_printf("return was: %d.\n", ret);
	 int err;
	 char err_buffer[80];
	 err = wolfSSL_get_error(ssl, 0);
	 System_printf("wolfSSL error: %d\n", err);
	 System_printf("wolfSSL error string: %s\n", wolfSSL_ERR_error_string(err, err_buffer));

	 END_LINE */

	if (ret == SSL_SUCCESS) {

		sockfd = wolfSSL_get_fd(ssl);

		/* Get a buffer to receive incoming packets. Use the default heap. */
		buffer = Memory_alloc(NULL, TCPPACKETSIZE, 0, &eb);

		if (buffer == NULL) {
			System_printf("tcpWorker: failed to alloc memory\n");
			exitApp(ctx);
		}

		/* Say hello to the server */
		while (flag) {
			if (wolfSSL_write(ssl, msg, strlen(msg)) != strlen(msg)) {
				ret = wolfSSL_get_error(ssl, 0);
				System_printf("Write error: %i.\n", ret);
			}
			while (internal_flag) {
				nbytes = wolfSSL_read(ssl, (char *) buffer, TCPPACKETSIZE);
				if (nbytes > 0) {
					internal_flag = false;
				}
			}
			/* success */
			System_printf("Heard: \"%s\".\n", buffer);
			wolfSSL_free(ssl);
			fdClose((SOCKET) sockfd);
			flag = false;
		}

		/* Free the buffer back to the heap */
		Memory_free(NULL, buffer, TCPPACKETSIZE);

		/*
		 *  Since deleteTerminatedTasks is set in the cfg file,
		 *  the Task will be deleted when the idle task runs.
		 */
		exitApp(ctx);

	} else {
		wolfSSL_free(ssl);
		fdClose((SOCKET) sockfd);
		System_printf("wolfSSL_connect failed.\n");
		fdCloseSession(TaskSelf());
		exitApp(ctx);
	}
}
Exemple #9
0
/*** mssAuthenticate - start a new session, overwriting previous
 *** (inherited) session information.
 ***/
int 
mssAuthenticate(char* username, char* password)
    {
    pMtSession s;
    char* encrypted_pwd;
    char* pwd;
    struct passwd* pw = NULL;
#ifdef HAVE_SHADOW_H
    struct spwd* spw;
#endif
    char salt[3];
    pFile altpass_fd;
    pLxSession altpass_lxs;
    char pwline[80];
    int t;
    int found_user;
    gid_t grps[16];
    int n_grps;

	/** Allocate a new session structure. **/
	s = (pMtSession)nmMalloc(sizeof(MtSession));
	if (!s) return -1;
	s->LinkCnt = 1;
	strncpy(s->UserName, username, 31);
	s->UserName[31]=0;
	strncpy(s->Password, password, 31);
	s->Password[31]=0;

	/** Attempt to authenticate. **/
	if (!strcmp(MSS.AuthMethod,"system"))
	    {
	    /** Use system auth (passwd/shadow files) **/
	    pw = getpwnam(s->UserName);
	    if (!pw)
		{
		memset(s, 0, sizeof(MtSession));
		nmFree(s,sizeof(MtSession));
		return -1;
		}
#ifdef HAVE_SHADOW_H
	    spw = getspnam(s->UserName);
	    if (!spw)
		{
#endif
		pwd = pw->pw_passwd;
#ifdef HAVE_SHADOW_H
		}
	    else
		{
		pwd = spw->sp_pwdp;
		}
#endif
	    strncpy(salt,pwd,2);
	    salt[2]=0;
	    encrypted_pwd = (char*)crypt(s->Password,pwd);
	    if (strcmp(encrypted_pwd,pwd))
		{
		memset(s, 0, sizeof(MtSession));
		nmFree(s,sizeof(MtSession));
		return -1;
		}
	    }
	else if (!strcmp(MSS.AuthMethod, "altpasswd"))
	    {
	    /** Sanity checking. **/
	    if (strchr(username,':'))
		{
		mssError(1, "MSS", "Attempt to use invalid username '%s'", username);
		memset(s, 0, sizeof(MtSession));
		nmFree(s,sizeof(MtSession));
		return -1;
		}

	    /** Open the alternate password file **/
	    altpass_fd = fdOpen(MSS.AuthFile, O_RDONLY, 0600);
	    if (!altpass_fd)
		{
		mssErrorErrno(1, "MSS", "Could not open auth file '%s'", MSS.AuthFile);
		memset(s, 0, sizeof(MtSession));
		nmFree(s,sizeof(MtSession));
		return -1;
		}
	    altpass_lxs = mlxOpenSession(altpass_fd, MLX_F_LINEONLY | MLX_F_EOF);

	    /** Scan it for the user name **/
	    found_user = 0;
	    while ((t = mlxNextToken(altpass_lxs)) != MLX_TOK_EOF)
		{
		if (t == MLX_TOK_ERROR)
		    {
		    mssError(0, "MSS", "Could not read auth file '%s'", MSS.AuthFile);
		    memset(s, 0, sizeof(MtSession));
		    nmFree(s,sizeof(MtSession));
		    mlxCloseSession(altpass_lxs);
		    fdClose(altpass_fd, 0);
		    return -1;
		    }
		mlxCopyToken(altpass_lxs, pwline, 80);
		if (strlen(username) < strlen(pwline) && !strncmp(pwline, username, strlen(username)) && pwline[strlen(username)] == ':')
		    {
		    found_user = 1;
		    break;
		    }
		}

	    /** Close the alternate password file **/
	    mlxCloseSession(altpass_lxs);
	    fdClose(altpass_fd, 0);

	    /** Did we find the user in the file? **/
	    if (found_user)
		{
		if (pwline[strlen(pwline)-1] == '\n')
		    pwline[strlen(pwline)-1] = '\0';
		pwd = pwline + strlen(username) + 1;
		encrypted_pwd = (char*)crypt(s->Password,pwd);
		if (strcmp(encrypted_pwd,pwd))
		    {
		    memset(s, 0, sizeof(MtSession));
		    nmFree(s,sizeof(MtSession));
		    return -1;
		    }
		}
	    else
		{
		memset(s, 0, sizeof(MtSession));
		nmFree(s,sizeof(MtSession));
		return -1;
		}
	    }
	else
	    {
	    mssError(1, "MSS", "Invalid auth method '%s'", MSS.AuthMethod);
	    return -1;
	    }

	/** Set the session information **/
	if (!strcmp(MSS.AuthMethod,"system"))
	    {
	    s->UserID = pw->pw_uid;
	    s->GroupID = pw->pw_gid;
	    initgroups(username, s->GroupID);
	    }
	else
	    {
	    s->UserID = geteuid();
	    s->GroupID = getegid();
	    }
	n_grps = getgroups(sizeof(grps) / sizeof(gid_t), grps);
	if (n_grps < 0 || n_grps > sizeof(grps) / sizeof(gid_t))
	    n_grps = 0;
	thSetParam(NULL,"mss",(void*)s);
	thSetParamFunctions(NULL, mssLinkSession, mssUnlinkSession);
	thSetSupplementalGroups(NULL, n_grps, grps);
	thSetGroupID(NULL,s->GroupID);
	thSetUserID(NULL,s->UserID);

	/** Initialize the error info **/
	xaInit(&(s->ErrList), 16);
	xhInit(&s->Params, 17, 0);

	/** Add to session list **/
	xaAddItem(&(MSS.Sessions), (void*)s);

    return 0;
    }