Exemple #1
0
static inline BYTE *readFormFromSocket( Socket_t *s, ULONG *length )
{
	BYTE *retData = NULL;
	char buffer[ MAX_SIZE ];
	int readSize;
	
	readSize = SocketRead( s, buffer, MAX_SIZE, 0 );
	DataForm *ldf = (DataForm *)buffer;
	
	// its our packet
	
	if( ldf->df_ID == ID_FCRE )
	{
		// message is bigger then buffer
		// we must read it all
		
		if( ldf->df_Size > MAX_SIZE )
		{
			unsigned int readedBytes = readSize;
			BufString *bs = BufStringNew();
			BufStringAddSize( bs, buffer, readSize );
			
			// reading bytes till end
			
			while( readedBytes <= ldf->df_Size )
			{
				readSize = SocketRead( s, buffer, MAX_SIZE, 0 );
				BufStringAddSize( bs, buffer, readSize );
				readedBytes += readSize;
			}
			
			FFree( bs );
			*length = bs->bs_Size;
			
			return (BYTE *)bs->bs_Buffer;
		}
		// message fits buffer
		else
		{
			if( ( retData = FCalloc( readSize, sizeof(BYTE) ) ) != NULL )
			{
				memcpy( retData, buffer, readSize );
				*length = readSize;
			}
			else
			{
 				ERROR("Cannot allocate memory for message buffer\n");
			}
		}
	}
	
	return retData;
}
Exemple #2
0
int main ()
{
    int s = SocketOpen ("vcan0", 1000, 1000);

    struct FrameBag bag;
    int yes = 0;
    gettimeofday (&t1, NULL);
    gettimeofday (&t2, NULL);
    while ( t2.tv_sec - t1.tv_sec < 1 )
    {
        if ( SocketRead (s, &bag, 1, 700) > 0
             && bag.Frame.can_id == 0x111
             && bag.Frame.can_dlc == 5
             && bag.Frame.data[0] == 1
             && bag.Frame.data[1] == 2
             && bag.Frame.data[2] == 3
             && bag.Frame.data[3] == 4
             && bag.Frame.data[4] == 5 )
        {
            yes = 1;
            break;
        }

        gettimeofday (&t2, NULL);
    }

    SocketClose (s);
    if (yes)
        printf ("Тесты пройдены.\n");
    else
        printf ("\n ~~~ !!!!!- ^ТЕСТ ЗАВАЛЕН^ -!!!! ~~~ \n\n");

    return yes ? 0 : -1;
}
Exemple #3
0
/**	
	Performs an HTTP POST operation to the path at the address / port specified.  The actual post contents 
  are found read from a given buffer and the result is returned in the same buffer.
  @param address The IP address of the server to post to.
  @param port The port on the server you're connecting to. Usually 80 for HTTP.
  @param hostname A string specifying the name of the host to connect to.  When connecting to a server
  that does shared hosting, this will specify who to connect with.
  @param path The path on the server to post to.
	@param buffer A pointer to the buffer to write from and read back into.  
	@param buffer_length An integer specifying the number of bytes to write.
	@param buffer_size An integer specifying the actual size of the buffer.
  @return status.

  \par Example
  \code
  // we'll post a test message to www.makingthings.com/post/path
  int addr = IP_ADDRESS( 72, 249, 53, 185); // makingthings.com is 72.249.53.185
  int bufLength = 100;
  char myBuffer[bufLength];
  sprintf( myBuffer, "A test message to post" );
  int result = WebClient_Post( addr, 80, "www.makingthings.com", "/post/path", 
                                    myBuffer, strlen("A test message to post"), bufLength );
  \endcode
*/
int WebClient_Post( int address, int port, char* hostname, char* path, char* buffer, int buffer_length, int buffer_size )
{
  char* b = WebClient_InternalBuffer;
  int buffer_read = 0;
  int wrote = 0;
  void* s = Socket( address, port );  
  if ( s != NULL )
  { 
    int send_len = snprintf( b, WEBCLIENT_INTERNAL_BUFFER_SIZE, 
                                "POST %s HTTP/1.1\r\n%s%s%sContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n", 
                                path, 
                                ( hostname != NULL ) ? "Host: " : "",
                                ( hostname != NULL ) ? hostname : "",
                                ( hostname != NULL ) ? "\r\n" : "",
                                buffer_length );
    if ( send_len > WEBCLIENT_INTERNAL_BUFFER_SIZE )
    {
      SocketClose( s );
      return CONTROLLER_ERROR_INSUFFICIENT_RESOURCES;
    }

    wrote = SocketWrite( s, b, send_len );
    if ( wrote == 0 )
    {
      SocketClose( s );
      return CONTROLLER_ERROR_WRITE_FAILED;
    }

    SocketWrite( s, buffer, buffer_length );
    
    int content_length = 0;
    int b_len;
    while ( ( b_len = SocketReadLine( s, b, WEBCLIENT_INTERNAL_BUFFER_SIZE ) ) )
    {
      if ( strncmp( b, "\r\n", 2 ) == 0 )
        break;
      if ( strncmp( b, "Content-Length", 14 ) == 0 )
        content_length = atoi( &b[ 16 ] );
    }
          
    if ( content_length > 0 && b_len > 0 )
    {
      char* bp = buffer;
      while ( ( b_len = SocketRead( s, bp, buffer_size - buffer_read ) ) )
      {
        buffer_read += b_len;
        bp += b_len;
        if ( buffer_read >= content_length )
          break;
      }
    }          

    SocketClose( s );
    return buffer_read;
  }
  else
    return CONTROLLER_ERROR_BAD_ADDRESS;
}
Exemple #4
0
void CZQCustomClient::DoRevice(pBlock data, int buflen)
{
	
	if (buflen > 0)
	{
		data->MsgBuf[buflen + 1] = '#0';
		char str[255];
		sprintf_s(str, 255, "BufferLen is :%d", buflen);
		OutputDebugString(str);
		SocketRead(data, buflen);
		if (m_socket != INVALID_SOCKET)
			ReadyReviceNextData(data);
		
	}
}
Exemple #5
0
bool File::ReadData(void* d, int size)
{
  if(size < 0)
    fprintf(stderr,"File::ReadData: invalid size %d\n",size);
	if(mode & FILEREAD)
	{
		switch(srctype)
		{
		case MODE_MYFILE:
		case MODE_EXTFILE:
			return FileRead(file,d,size);
		case MODE_MYDATA:
		case MODE_EXTDATA:
			if(datapos + size > datasize)
				return false;
			memcpy(d, datafile+datapos, size);
			datapos += size;
			return true;
		case MODE_TCPSOCKET:
		case MODE_UDPSOCKET:
		  {
		    char* buffer = (char*)d;
		    int totalread = 0;
		    while(totalread < size) {
		      int n=SocketRead(socket,buffer+totalread,size-totalread);
		      if(n == 0) {
			printf("File(socket): socketRead returned 0, connection shutdown\n");
			return false;
		      }
		      if(n < 0) {
			if(errno==EWOULDBLOCK) {
			  ThreadSleep(0.001);
			  //just spin?
			  continue;
			}
			perror("Unhandled error in socket read");
			return false;
		      }
		      totalread += n;
		    }
		    assert(totalread == size);
		    return true;
		  }
		}
	}
	return false;
}
Exemple #6
0
int ConnRead(TConn *c,uint32 timeout)
{
	/* sanity */
	if (!c) {
		return FALSE;
	}

/* CODE_PROBE_1("ConnRead - START(%x)",c); */
	while (SocketWait(&(c->socket),TRUE,FALSE,timeout*1000)==1)
	{
		int x = c->maxbuffersize - c->buffersize;
		int y = 0;
		
/* CODE_PROBE_1("ConnRead - READ(%x)",c); */
		if ((y=SocketRead(&(c->socket),c->buffer+c->buffersize,x))>0)
		{
#if 0
				int i = 0;
				char d = 0;

				for (i=0;i<y;i++)
				{
					d=*(c->buffer+c->buffersize+i);
					if (d<32)
						printf("[%d]",d);
					else
						printf("%c",d);
				};
				printf("\n");
#endif
				c->inbytes+=y;
				c->buffersize+=y;
				c->buffer[c->buffersize]='\0';
/* CODE_PROBE_1( "ConnRead - END(%x) - True",c); */
				return TRUE;
		} else {
			c->connected = FALSE;
		}

		break;
	}

/* CODE_PROBE_1( "ConnRead - End(%x) - False",c); */
	return FALSE;
}
Exemple #7
0
INT GetNextUGEvent (EVENT *theEvent, INT Eventmask)
{
  INT len;

  BUFSTART;
  BUFINT(DC_GetNextUGEvent);
  BUFEND;
  /*
          SocketWriteData(theSocket, theEvent, sizeof(EVENT));
   */
  SocketWriteINT(theSocket, Eventmask);

  len = SocketReadINT(theSocket);
  if (len==0)
    return(0);

  /* an event has occured */
  SocketRead(theSocket, (char *)theEvent, len);
  return(0);
}
Exemple #8
0
DWORD SocketReadThread(LPVOID pContext)
{
	UINT16 ret=0;
	BYTE *search_sync_ptr = NULL;
	BYTE *search_end_ptr  = NULL;

	while (!bKillSocketThread)
	{
		ret = SocketRead(&ReadBuff[iReadBuffLen],SOCKET_READ_MAX_BUFF_LEN - iReadBuffLen);
		if (ret > 0)
		{
			iReadBuffLen += (UINT16)ret;
			search_sync_ptr = &ReadBuff[0];
			search_end_ptr  = &ReadBuff[iReadBuffLen];

			dealDataStream(search_sync_ptr,search_end_ptr);
		}
	}

	return 0;
}
Exemple #9
0
////////////////////////////////////////////////////////////////////////////////////////////
/// Read the POST data section of a web request from a socket
/// Both input streams read pointers must be set at the beginning of the POST data.
/// \param strError Output error string
/// \param pClientSocket the socket to read
/// \return True if success, False if fail.
////////////////////////////////////////////////////////////////////////////////////////////
bool HTTPRequestHeader::ReadPostData(string& strError, NetSocket* pClientSocket)
{
    unsigned int nContentLength = StartReadPostData(strError);

    if (nContentLength == 0)
    {
        return false;
    }

    gtSize_t nRead = 0;

    // Read data from a socket
    nRead = SocketRead(pClientSocket, m_pPostData, nContentLength);

    // Terminate the buffer.
    m_pPostData[nRead] = '\0';

    //// Keep in for Debugging
    //StreamLog::Ref() << "READ IN SHADER:" << pPostDataBuffer << "\n";
    //printf ( "Read shader from web request: \n%s\n", m_pPostData);
    return true;
}
Exemple #10
0
int ConnReadRaw(TConn *c, char *buffer, uint32 len, uint32 timeout, int *readLen)
{
	int bufflen = 0;
	uint32 toread = len;

	/* sanity */
	if (!c || !buffer || !readLen) {
		return FALSE;
	}

	bufflen = c->buffersize - c->bufferpos;

	if (bufflen > 0)
	{
		if (toread > (size_t)bufflen)
			toread = bufflen;
		memcpy(buffer, c->buffer + c->bufferpos, toread);
		c->bufferpos += toread;
		*readLen = toread;
		return TRUE;
	}
	else
	{
		
		/* we have to read from the socket */
		if (SocketWait(&(c->socket),TRUE,FALSE,timeout*1000)==1)
		{
			uint32 avail=SocketAvailableReadBytes(&(c->socket));
			if (avail < toread)
				toread = avail;
			*readLen = SocketRead(&(c->socket), buffer, toread);
			if (*readLen > 0)
				return TRUE;
		}
		*readLen = 0;
		return FALSE;
	}
}
Exemple #11
0
abyss_bool
ConnRead(TConn *  const connectionP,
         uint32_t const timeout) {
    /*----------------------------------------------------------------------------
       Read some stuff on connection *connectionP from the socket.

       Don't wait more than 'timeout' seconds for data to arrive.  Fail if
       nothing arrives within that time.
    -----------------------------------------------------------------------------*/
    time_t const deadline = time(NULL) + timeout;

    abyss_bool cantGetData;
    abyss_bool gotData;

    cantGetData = FALSE;
    gotData = FALSE;

    while (!gotData && !cantGetData) {
        int const timeLeft = deadline - time(NULL);

        if (timeLeft <= 0)
            cantGetData = TRUE;
        else {
            int rc;

            rc = SocketWait(connectionP->socketP, TRUE, FALSE,
                            timeLeft * 1000);

            if (rc != 1)
                cantGetData = TRUE;
            else {
                uint32_t bytesAvail;

                bytesAvail = SocketAvailableReadBytes(connectionP->socketP);

                if (bytesAvail <= 0)
                    cantGetData = TRUE;
                else {
                    uint32_t const bytesToRead =
                        MIN(bytesAvail, bufferSpace(connectionP)-1);

                    uint32_t bytesRead;

                    bytesRead = SocketRead(
                                    connectionP->socketP,
                                    (unsigned char*)connectionP->buffer + connectionP->buffersize,
                                    bytesToRead);
                    if (bytesRead > 0) {
                        traceSocketRead(connectionP, bytesRead);
                        connectionP->inbytes += bytesRead;
                        connectionP->buffersize += bytesRead;
                        connectionP->buffer[connectionP->buffersize] = '\0';
                        gotData = TRUE;
                    }
                }
            }
        }
    }
    if (gotData)
        return TRUE;
    else
        return FALSE;
}
Exemple #12
0
DataForm *CommServiceSendMsg( CommService *s, DataForm *df )
{
	DataForm *retDF = NULL;
	
	DEBUG("CommunicationSendmesage\n");
	if( s && df )
	{
		char buffer[ MAX_SIZE ];
		
		if( df[ 0 ].df_ID == ID_FCRE && df[ 1 ].df_ID == ID_QUER )
		{
			BYTE *targetName = (BYTE *)(df+1);
			targetName += COMM_MSG_HEADER_SIZE;
			
			DEBUG("Message destination %s  size %ld\n", targetName, df[ 1 ].df_Size );
			
			// send message to all servers
			
			if( strncmp( (char *)targetName, "ALL", 3 ) == 0 )
			{
				
				MsgItem tags[] = {
					{ ID_FCRE, 0, NULL },
					{ ID_SVIN, 0, NULL },
					{ TAG_DONE, TAG_DONE, TAG_DONE }
				};
			
				DataForm *ldf = DataFormNew( tags );
				
				CommFCConnection *lc = s->s_FCConnections;
				while( lc != NULL )
				{
					//TODO test message , should be removed
					SocketWrite( lc->cfcc_Socket, (char *)df, df->df_Size );//"hello", 5 );
					DEBUG("CommunicationServiceClient Sending message hello\n");
					ULONG sockReadSize = 0;
/*
					MsgItem loctags[] = {
						//{ ID_FCRE, 0, NULL },
						//{ ID_SVIN, 0, NULL },
						{ ID_SNAM, 64*sizeof(BYTE), lc->cfcc_Id },
						{ TAG_DONE, TAG_DONE, TAG_DONE }
					};
			
					INFO("joining messages\n");
					
					DataForm *serverdf = DataFormNew( loctags );
	*/				
					BYTE *lsdata = readFormFromSocket( lc->cfcc_Socket, &sockReadSize );
					
					DataFormAdd( &ldf, lsdata, sockReadSize );
					//DEBUG("Added new server to answer serverdfsize %ld sockreadsize %ld\n", serverdf->df_Size, sockReadSize );
					
					FFree( lsdata );
					
					//DataFormAddForm( &ldf, serverdf );
					
					//DataFormDelete( serverdf );
					
					//sockReadSize = SocketRead( lc->cfcc_Socket, buffer, MAX_SIZE, 0 );
					DEBUG("Received information in bytes %ld\n", sockReadSize );
					//int writeSize = write( service->s_recvPipe[ 1 ], buffer, sockReadSize );
			
					//DEBUG("Message received '%s'\n", buffer );
					lc = (CommFCConnection *)lc->node.mln_Succ;
				}
				
				return ldf;
			}
			else	// send message to one target
			{
				// find server and send message
				
				CommFCConnection *lc = s->s_FCConnections;
				while( lc != NULL )
				{
					if( strncmp( (char *)targetName, (char *)lc->cfcc_Id, df[ 1 ].df_Size ) == 0 )
					{
						//TODO test message , should be removed
						SocketWrite( lc->cfcc_Socket, (char  *)df, df->df_Size );//"hello", 5 );
						DEBUG("CommunicationServiceClient Sending message hello\n");
						int sockReadSize = 0;

						sockReadSize = SocketRead( lc->cfcc_Socket, buffer, MAX_SIZE, 0 );
						DEBUG("Received information in bytes %d\n", sockReadSize );
						//int writeSize = write( service->s_recvPipe[ 1 ], buffer, sockReadSize );
			
						//DEBUG("Message received '%s'\n", buffer );
					}
					lc = (CommFCConnection *)lc->node.mln_Succ;
				}
			}
		}
		else
		{
			ERROR("Message is broken, cannot send it\n");
		}

		DEBUG("Communication resources free\n");
	}
	
	return retDF;
}
Exemple #13
0
/**	
	Performs an HTTP GET operation to the path at the address / port specified.  
  
  Reads through the HTTP header and copies the data into the buffer you pass in.  Because
  sites can often be slow in their responses, this will wait up to 1 second (in 100 ms. intervals)
  for data to become available.

  Some websites seem to reject connections occassionally - perhaps because we don't supply as
  much info to the server as a browser might, for example.  Simpler websites should be just fine.
  
  Note that this uses lots of printf style functions and may require a fair amount of memory to be allocated
  to the task calling it.  The result is returned in the specified buffer.

	@param address The IP address of the server to get from.  Usually created using the IP_ADDRESS( ) macro.
  @param port The port to connect on.  Usually 80 for HTTP.
  @param hostname A string specifying the name of the host to connect to.  When connecting to a server
  that does shared hosting, this will specify who to connect with.
  @param path The path on the server to connect to.
  @param buffer A pointer to the buffer read back into.  
	@param buffer_size An integer specifying the actual size of the buffer.
  @return the number of bytes read, or < 0 on error.

  \par Example
  \code
  int addr = IP_ADDRESS( 72, 249, 53, 185); // makingthings.com is 72.249.53.185
  int bufLength = 100;
  char myBuffer[bufLength];
  int getSize = WebClient_Get( addr, 80, "www.makingthings.com", "/test/path", myBuffer, bufLength );
  \endcode
  Now we should have the results of the HTTP GET from \b www.makingthings.com/test/path in \b myBuffer.
*/
int WebClient_Get( int address, int port, char* hostname, char* path, char* buffer, int buffer_size )
{
  char* b = WebClient_InternalBuffer;
  struct netconn *s = Socket( address, port );  
  if ( s != NULL )
  {
    // construct the GET request
    int send_len = snprintf( b, WEBCLIENT_INTERNAL_BUFFER_SIZE, "GET %s HTTP/1.1\r\n%s%s%s\r\n", 
                                path,
                                ( hostname != NULL ) ? "Host: " : "",
                                ( hostname != NULL ) ? hostname : "",
                                ( hostname != NULL ) ? "\r\n" : ""  );
    if ( send_len > WEBCLIENT_INTERNAL_BUFFER_SIZE )
    {
      SocketClose( s );
      return CONTROLLER_ERROR_INSUFFICIENT_RESOURCES;
    }
    
    // send the GET request
    if(!SocketWrite( s, b, send_len ))
    {
      SocketClose( s );
      return CONTROLLER_ERROR_WRITE_FAILED;
    }

    int content_length = 0;
    // read through the response header to get to the data, and pick up the content-length as we go
    int buffer_length;
    while ( ( buffer_length = SocketReadLine( s, b, WEBCLIENT_INTERNAL_BUFFER_SIZE ) ) )
    {
      if ( strncmp( b, "\r\n", 2 ) == 0 )
        break;
      if ( strncmp( b, "Content-Length", 14 ) == 0 )
        content_length = atoi( &b[ 15 ] );
    }
    
    // read the data into the given buffer until there's none left, or the passed in buffer is full
    int total_bytes_read = 0;
    int buf_remaining = buffer_size;
    if ( content_length > 0 && buffer_length > 0 )
    {
      char* bp = buffer;
      while( total_bytes_read < buffer_size && total_bytes_read < content_length )
      {
        int avail = SocketBytesAvailable(s);
        if(!avail) // sometimes the connection can be slooooow, sleep a bit and try again
        {
          int times = 10;
          while(times--)
          {
            Sleep(100);
            if((avail = SocketBytesAvailable(s)))
              break;
          }
        }
        if(!avail) // if we still didn't get anything, bail
          break;

        if(avail > buf_remaining) // make sure we don't read more than can fit
          avail = buf_remaining;
        buffer_length = SocketRead( s, bp, avail );
        if(!buffer_length) // this will be 0 when we get a read error - bail in that case
          break;

        // update counts
        buf_remaining -= buffer_length;
        total_bytes_read += buffer_length;
        bp += buffer_length;
      }
    }
          
    SocketClose( s );
    return total_bytes_read;
  }
  else
    return CONTROLLER_ERROR_BAD_ADDRESS;
}
Exemple #14
0
int CHttpThread::ReadHttpReq()
{
    int iRet;
	int pos;
	int len;
	char * p;
	int contentpos;
	int i,j;

	m_szHttpHead[0]='\0';
    pos=0;
	p=strstr(m_szHttpHead,"\r\n\r\n");
    while (p==NULL)
    {
        len=recv(m_sockfd,&m_szHttpHead[pos],1023,0);
		if(len<=0)
		{
		    return -1;
		}
        //printf("len=%d\n",len);
        pos+=len;
		m_szHttpHead[pos]=0;
		p=strstr(m_szHttpHead,"\r\n\r\n");
    }
	if(pos==0)
	{
	    return -1;
	}
	m_szHttpHead[pos]=0;
	contentpos=p - m_szHttpHead + 4;
	p[2]=0;

	printf("========================http head begin =================================\n");
	printf("%s",m_szHttpHead);
	printf("========================http head end =================================\n");

	m_szHttpContent[0]=0;
	for(j=0,i=contentpos;i<pos;i++)
	{
	    m_szHttpContent[j]=m_szHttpHead[i];
		j++;
	}
	m_szHttpContent[j]=0;
	iRet= ParseHttpHead(m_szHttpHead,&m_HttpHead);

	if(m_HttpHead.m_ContentLength<0 || m_HttpHead.m_ContentLength>MAXHTTPPACKETLEN)
	{
	    return -1;
	}

	if(m_HttpHead.m_ContentLength==0)
	{
	    return 0;
	}

	if(m_HttpHead.m_ContentLength - j>0)
	{
		iRet=SocketRead(m_sockfd,&m_szHttpContent[j],m_HttpHead.m_ContentLength - j);
		if(iRet<=0)
		{
			return -1;
		}
		m_szHttpContent[iRet+j]=0;
	}

	printf("============================http content begin ===============================\n");
	printf("%s\n",m_szHttpContent);
	printf("============================http content end   ===============================\n");

	return 0;
}