Ejemplo n.º 1
0
void testEnc() {
  origLen = random() % 81;
  for (int i = 0; i < origLen; i++) {
    origBuf[i] = random() % 256;
  }

  encLen = ElektronHelper::MNMDataToSysex(origBuf, encBuf, origLen, sizeof(encBuf));

  decLen = ElektronHelper::MNMSysexToData(encBuf, decBuf, encLen, sizeof(decBuf));

  printf("origLen: %d, encLen: %d, decLen: %d\n", origLen, encLen, decLen);
  
  if (origLen != decLen) {
    printf("wrongLen\n");
    printf("orig\n");
    hexDump(origBuf, origLen);
    printf("encoded\n");
    hexDump(encBuf, encLen);
    printf("decoded\n");
    hexDump(decBuf, decLen);
  }


  for (int i = 0; i < origLen; i++) {
    if (origBuf[i] != decBuf[i]) {
      printf("%.4x: %.2x was %.2x\n", i, decBuf[i], origBuf[i]);
    }
  }

}
Ejemplo n.º 2
0
bool SynscanDriver::sendCommand(const char * cmd, char * res, int cmd_len, int res_len)
{
    int nbytes_written = 0, nbytes_read = 0, rc = -1;

    tcflush(PortFD, TCIOFLUSH);

    if (cmd_len > 0)
    {
        char hex_cmd[SYN_RES * 3] = {0};
        hexDump(hex_cmd, cmd, cmd_len);
        LOGF_DEBUG("CMD <%s>", hex_cmd);
        rc = tty_write(PortFD, cmd, cmd_len, &nbytes_written);
    }
    else
    {
        LOGF_DEBUG("CMD <%s>", cmd);
        rc = tty_write_string(PortFD, cmd, &nbytes_written);
    }

    if (rc != TTY_OK)
    {
        char errstr[MAXRBUF] = {0};
        tty_error_msg(rc, errstr, MAXRBUF);
        LOGF_ERROR("Serial write error: %s.", errstr);
        return false;
    }

    if (res == nullptr)
        return true;

    if (res_len > 0)
        rc = tty_read(PortFD, res, res_len, SYN_TIMEOUT, &nbytes_read);
    else
        rc = tty_nread_section(PortFD, res, SYN_RES, SYN_DEL, SYN_TIMEOUT, &nbytes_read);

    if (rc != TTY_OK)
    {
        char errstr[MAXRBUF] = {0};
        tty_error_msg(rc, errstr, MAXRBUF);
        LOGF_ERROR("Serial read error: %s.", errstr);
        return false;
    }

    if (res_len > 0)
    {
        char hex_res[SYN_RES * 3] = {0};
        hexDump(hex_res, res, res_len);
        LOGF_DEBUG("RES <%s>", hex_res);
    }
    else
    {
        LOGF_DEBUG("RES <%s>", res);
    }

    tcflush(PortFD, TCIOFLUSH);

    return true;
}
Ejemplo n.º 3
0
static BOOL
initSession( SOCKET sock )
{
    BYTE	buffer[ 1024 ];
    DWORD	length;
    BOOL	aes256 = FALSE;

    aes256 = (aesMaxKey >= 256);
    buffer[ 0 ] = aes256 ? 1 : 0;

    if ( ! (length = encodePK( sizeof( buffer ) - 1, &buffer[1] )) )
	return( FALSE );

    if ( verbose )
    {
	printf( "Session Initiation: \n" );
	hexDump( length + 1, buffer );
    }

    if ( ! sendBytes( sock, buffer, length + 1 ) )
	return( FALSE );

    if ( ! receiveBytes( sock, buffer, sizeof( buffer ), &length ) )
	return( FALSE );

    if ( ! length )
    {
	fprintf( stderr, "No session response from server\n" );
	return( FALSE );
    }

    if ( verbose )
    {
	printf( "Session Response: \n" );
	hexDump( length, buffer );
    }

    switch( buffer[ 0 ] )
    {
    case 0 :  aes256 = FALSE;	break;
    case 1 :
	if ( aes256 )  break;

	/*
	** Fall through for unsupported AES key length.
	*/

    default:
	fprintf( stderr, "Invalid AES key length returned: %d\n", buffer[0] );
	return( FALSE );
    }

    if ( ! decodeSK( aes256, length - 1, &buffer[1] ) )
	return( FALSE );

    return( TRUE );
}
Ejemplo n.º 4
0
// Output hexdump to a QString
QString QWSHexDump::toString() {
    QString result;
    QTextStream strm(&result, QFile::WriteOnly);
    outstrm = &strm;
    hexDump();
    return result;
}
Ejemplo n.º 5
0
void Logger::dump(LogItem item)
{
    QString varName = item.value(0).toString();
    QByteArray ba = item.value(1).toByteArray();
    QString typeName = item.value(1).typeName();
    int bytes = item.value(2).toInt();
    LogLevel level(item.getLevel());

    switch (int(level))
    {
    case LogLevel::DumpVar:
        item.setValue(3, typeName);
        item.setMessage("%1 = {%2} %4 %3");
        break;

    case LogLevel::DumpHex:
        item.setValue(3, typeName);
        item.setValue(4, hexDump(ba));
        item.setMessage("%1 = %4 %3 %5 %2!");
        break;

    default:
        qWarning("Logger::dump() with wrong level");
        return;
    }

    enqueue(item);
}
Ejemplo n.º 6
0
static int write_out(const void *buffer, size_t size, void *app_key)
{
	FILE *out_fp = app_key;
	size_t wrote;

	hexDump("", buffer, size);
	wrote = fwrite(buffer, 1, size, out_fp);

	return (wrote == size) ? 0 : -1;
}
Ejemplo n.º 7
0
/* Loop until it is explicitly halted or the network is lost, then clean up. */
static int run_loop() {
	for (;;) {
		if (mode == receiver && rfm69->receiveDone()) {
			LOG("Received something...\n");
			// store the received data localy, so they can be overwited
			// This will allow to send ACK immediately after
			uint8_t data[RF69_MAX_DATA_LEN]; // recv/xmit buf, including header & crc bytes
			uint8_t dataLength = rfm69->DATALEN;
			memcpy(data, (void *)rfm69->DATA, dataLength);
			uint8_t theNodeID = rfm69->SENDERID;
			uint8_t targetID = rfm69->TARGETID; // should match _address
			uint8_t PAYLOADLEN = rfm69->PAYLOADLEN;
			uint8_t ACK_REQUESTED = rfm69->ACK_REQUESTED;
			uint8_t ACK_RECEIVED = rfm69->ACK_RECEIVED; // should be polled immediately after sending a packet with ACK request
			int16_t RSSI = rfm69->RSSI; // most accurate RSSI during reception (closest to the reception)
			LOG("ACK REQUESTED: %d, targetID %d, theConfig.nodeId %d\n", ACK_REQUESTED, targetID, theConfig.nodeId);
			if (ACK_REQUESTED  && targetID == theConfig.nodeId) {
				// When a node requests an ACK, respond to the ACK
				// but only if the Node ID is correct
				rfm69->sendACK();
			}//end if radio.ACK_REQESTED
	
			LOG("[%d] to [%d] ", theNodeID, targetID);

			if (dataLength != sizeof(Payload)) {
				LOG("Invalid payload received, not matching Payload struct! %d - %d\r\n", dataLength, sizeof(Payload));
				hexDump(NULL, data, dataLength, 16);		
			} else {
				theData = *(Payload*)data; //assume radio.DATA actually contains our struct and not something else

				LOG("Received Node ID = %d Device ID = %d Time = %d  RSSI = %d var2 = %f var3 = %f\n",
					theData.nodeID,
					theData.sensorID,
					theData.var1_usl,
					RSSI,
					theData.var2_float,
					theData.var3_float
				);
			}  
		} //end if radio.receive
		
    if (mode == sender) {
  		counter = counter + 1;
  		if (counter % 20 == 0) {
  			LOG("Sending test message\n");
  			send_message();
  		} else {
  			usleep(100*1000);
  		}
    } 
		
	}

}
Ejemplo n.º 8
0
/*---  FUNCTION  ----------------------------------------------------------------------*
 *         Name:  X509_DecodeSignatureAlgorithm
 *  Description:  This function will detect and decode the signature algorithm. It will
 *                also extract any parameters that are required for the algorithm.
 *-------------------------------------------------------------------------------------*/
static	unsigned int X509_DecodeSignatureAlgorithm ( ASN1_OBJECT* object, SIGNATURE* algorithm )
{
	unsigned int	count;
	unsigned int	result = 0;
	unsigned int	have_prameters;
	ASN1_OBJECT		sub_item;

	if (ASN1_GetNextObject(object,&sub_item) && ASN1_CHECK_OBJECT(sub_item,A1T_PRIMITIVE,A1C_UNIVERSAL,A1UC_OBJECT_IDENTIFIER_TYPE) )
	{
		for (count=0;count < NUMBER_OF_SIGNATURE_ALGOS;count++)
		{
			if (sub_item.length == sig_matrix[count].sig_length && memcmp(sub_item.data,sig_matrix[count].sig_string,sub_item.length) == 0)
			{
				/* found the signature */
				algorithm->algorithm = sig_matrix[count].algorithm;
				break;
			}
		}
	}

	have_prameters = ASN1_GetNextObject(object,&sub_item) && !ASN1_CHECK_OBJECT(sub_item,A1T_PRIMITIVE,A1C_UNIVERSAL,A1UC_NULL_TYPE);

	/* lets now check for any parameters that exist */
	switch (algorithm->algorithm)
	{
		case X509SA_RSA_MD2:
		case X509SA_RSA_MD5:
		case X509SA_RSA_SHA1:
			if (!have_prameters)
			{
				/* the RSA's don't have parameters */
				result = 1;
			}
			break;

		case X509SA_DSA_SHA1:
			/* find any parameters - this should depend on the type */
			while (ASN1_GetNextObject(object,&sub_item) && !ASN1_CHECK_OBJECT(sub_item,A1T_PRIMITIVE,A1C_UNIVERSAL,A1UC_NULL_TYPE))
			{
				printf("We have parameters: \n");
				hexDump(sub_item.data,sub_item.length);
			}
			break;

		case X509SA_ECDSA_SHA1:
			break;
	}

	return result;
}
Ejemplo n.º 9
0
void printBuf() {
  hexDump(MidiSysex.data + 3, MidiSysex.recordLen - 3);
  if (!inCallback) {
    m_memcpy(origBuf, MidiSysex.data, MidiSysex.recordLen);
    origLen = MidiSysex.recordLen;
  } else {
    printf("origLen: %d, newLen: %d\n", origLen, MidiSysex.recordLen);
    for (int i = 0; i < origLen; i++) {
      if (MidiSysex.data[i + 3] != origBuf[i + 3]) {
	printf("%.3x diff: %.2x was %.2x\n", i, MidiSysex.data[i + 3], origBuf[i + 3]);
      }
    }
  }
}
void AbstractResponseHandler::handleResponse(osiSockAddr* responseFrom,
        Transport::shared_pointer const & /*transport*/, int8 version, int8 command,
        size_t payloadSize, ByteBuffer* payloadBuffer) {
    if(_debugLevel >= 3) {   // TODO make a constant of sth (0 - off, 1 - debug, 2 - more/trace, 3 - messages)
        char ipAddrStr[48];
        ipAddrToDottedIP(&responseFrom->ia, ipAddrStr, sizeof(ipAddrStr));

        ostringstream prologue;
        prologue<<"Message [0x"<<hex<<(int)command<<", v0x"<<hex;
        prologue<<(int)version<<"] received from "<<ipAddrStr;

        hexDump(prologue.str(), _description,
                (const int8*)payloadBuffer->getArray(),
                payloadBuffer->getPosition(), static_cast<int>(payloadSize));
    }
}
Ejemplo n.º 11
0
//----------------------------- FUNCTION -------------------------------------*
int
    TrcHexDump(WORD wLevel, BYTE* pby, int nBytes, int nShowBytes /*= -1*/)
/*>>>>
print hex dump of <pby>

I   wLevel:     trace level
I   pby:        ptr to byte array to dump
I   nBytes:     number of bytes in byte array
I   nShowBytes: show up to <nShowBytes> bytes;
                if -1, use default max length <s_nMaxDumpWidth>

Result
  E_TRC_OK
  E_TRC_NOT_INITIALIZED
  E_TRC_BAD_LEVEL
  E_TRC_NO_RESOURCE
<<<<*/
{
    if (!s_bInitialized) {
        return E_TRC_NOT_INITIALIZED;
    }

    if (s_traceMode == noTrace) {
        // trace mode is disabled
        return E_TRC_OK;
    }

    if ((wLevel & s_wLevel) == 0) {
        // this level is not activated
        return E_TRC_OK;
    }

    if (pby == NULL) {
        return E_TRC_NO_RESOURCE;
    }

    EnterCriticalSection(&s_csTrcFile);
    TrcPrint(wLevel, _T("HexDump: "));
    if (nShowBytes < 0) {
        nShowBytes = s_nMaxDumpWidth;
    }
    hexDump(pby, nBytes, nShowBytes);
    LeaveCriticalSection(&s_csTrcFile);
    return E_TRC_OK;
}
Ejemplo n.º 12
0
std::string binarize( const std::string & path, const std::string & name )
{
    FILE * f = fopen(path.c_str(),"rb");
    if(!f)
        return "";
    
    size_t sz = getFileSize(f);
    std::vector<unsigned char> buf(sz);
    fread(&buf[0],1,sz,f);
    std::string bufs = hexDump(&buf[0], sz);
    
    std::stringstream sizes, defs;
    sizes << "size_t " << name <<  "_size=" << (int)sz << ";";
    defs << "\nunsigned char " << name << "[] = \n{" << bufs << "\n};";
    
    fclose(f);
    return sizes.str() + defs.str();
}
Ejemplo n.º 13
0
static void
keyInfo( HCRYPTKEY key )
{
    BYTE	buffer[ 1024 ];
    DWORD	length;

    length = sizeof( buffer );

    if ( ! CryptGetKeyParam( key, KP_BLOCKLEN, buffer, &length, 0 ) )
    {
	fprintf( stderr, "CryptGetKeyParam BLOCKLEN failed: 0x%x\n", GetLastError() );
	exit( 1 );
    }

    printf( "Key Block Size: %d\n", *(DWORD *)buffer / 8 );
    length = sizeof( buffer );

    if ( ! CryptGetKeyParam( key, KP_MODE, buffer, &length, 0 ) )
    {
	fprintf( stderr, "CryptGetKeyParam MODE failed: 0x%x\n", GetLastError() );
	exit( 1 );
    }

    printf( "Key Mode: %d\n", *(DWORD *)buffer );
    length = sizeof( buffer );

    if ( ! CryptGetKeyParam( key, KP_PADDING, buffer, &length, 0 ) )
    {
	fprintf( stderr, "CryptGetKeyParam PADDING failed: 0x%x\n", GetLastError() );
	exit( 1 );
    }

    printf( "Key Padding Type: %d\n", *(DWORD *)buffer );
    length = sizeof( buffer );

    if ( ! CryptGetKeyParam( key, KP_IV, buffer, &length, 0 ) )
    {
	fprintf( stderr, "CryptGetKeyParam PADDING failed: 0x%x\n", GetLastError() );
	exit( 1 );
    }

    printf( "Key IV: \n" );
    hexDump( length, buffer );
}
Ejemplo n.º 14
0
void onSongMessageCallback() {
  printBuf();
      
  if (!song.fromSysex(MidiSysex.data, MidiSysex.recordLen)) {
    fprintf(stderr, "error parsing song\n");
  } else {
    printf("parsed song!\n");
  }
  printf("\n");

  if (!inCallback) {
    inCallback = true;
    uint16_t len = song.toSysex(sysexBuf, sizeof(sysexBuf));
    hexDump(sysexBuf, len);
    parseSysex(sysexBuf, len);
  }

  inCallback = false;
}
Ejemplo n.º 15
0
std::string hexDump(const void* ptr, size_t size) {
  std::ostringstream os;
  hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
  return os.str();
}
Ejemplo n.º 16
0
static BOOL
clientRequest( SOCKET sock, char *host, u_short port )
{
    BYTE	buffer[ 1024 ];
    BYTE	*ptr, *end;
    DWORD	length;
    BOOL	echo = FALSE;

    sprintf_s( buffer, sizeof( buffer ), REQUEST_TEMPLATE, host, port );
    length = strlen( buffer );

    if ( ! (length = encode( length, buffer, sizeof( buffer ) )) )
	return( FALSE );

    if ( verbose )
    {
	printf( "Client Request: \n" );
	hexDump( length, buffer );
    }

    if ( ! sendBytes( sock, buffer, length ) )
	return( FALSE );

    do
    {
	if ( ! receiveBytes( sock, buffer, sizeof( buffer ), &length ) )
	    return( FALSE );

	if ( ! length )
	{
	    fprintf( stderr, "No response from server\n" );
	    break;
	}

	if ( verbose )
	{
	    printf( "Server Response: \n" );
	    hexDump( length, buffer );
	}

	if ( ! (length = decode( length, buffer, sizeof( buffer ) )) )
	    return( FALSE );

	ptr = buffer;
	end = ptr + length;
	*end = 0;

	while( ptr < end )
	{
	    BYTE *eol, save;

	    for( eol = ptr; *eol  &&  *eol != '\n'; eol++ )  /* DO NOTHING */;
	    eol++;
	    save = *eol;
	    *eol = 0;

	    /*
	    ** Display response between 'BEGIN' and 'END'
	    */
	    if ( ! echo )
	    {
		/* Echo starts with 'BEGIN' */
		if ( ! strcmp( ptr, "BEGIN\r\n" )  ||  ! strcmp( ptr, "BEGIN\n" ) )
		    echo = TRUE;
	    }
	    else
	    {
		/* Echo finishes with 'END' */
		if ( ! strcmp( ptr, "END\r\n" )  ||  ! strcmp( ptr, "END\n" ) )
		    break;

		printf( "%s", ptr );
	    }

	    *eol = save;
	    ptr = eol;
        }
    } while( FALSE );

    return( TRUE );
}
Ejemplo n.º 17
0
/*---  FUNCTION  ----------------------------------------------------------------------*
 *         Name:  X509_DecodeExtensions
 *  Description:  This function will decode the extensions.
 *-------------------------------------------------------------------------------------*/
unsigned int	X509_DecodeExtensions ( ASN1_OBJECT* object, X509_CERTIFICATE* certificate )
{
	unsigned int	result = 1;
	unsigned int	count;
	unsigned int	critical = 0;
	ASN1_OBJECT		item;
	ASN1_OBJECT		sub_item;
	ASN1_OBJECT		element;
	ASN1_OBJECT		payload;
	ASN1_OBJECT		sub_element;
	ASN1_OBJECT		sub_sub_element;		/* f**king XMLers */



	if (ASN1_GetNextObject(object,&item) && ASN1_CHECK_OBJECT(item,A1T_CONSTRUCTED,A1C_UNIVERSAL,A1UC_SEQUENCE_TYPE))
	{
		while (ASN1_GetNextObject(&item,&sub_item) && ASN1_CHECK_OBJECT(sub_item,A1T_CONSTRUCTED,A1C_UNIVERSAL,A1UC_SEQUENCE_TYPE))
		{
			if (ASN1_GetNextObject(&sub_item,&element) && ASN1_CHECK_OBJECT(element,A1T_PRIMITIVE,A1C_UNIVERSAL,A1UC_OBJECT_IDENTIFIER_TYPE) )
			{
				if (ASN1_GetNextObject(&sub_item,&payload) && ASN1_CHECK_OBJECT(payload,A1T_PRIMITIVE,A1C_UNIVERSAL,A1UC_BOOLEAN_TYPE) )
				{
					/* X509 are C**kMonkeys!!! Why not just make the critical boolean Mandatory!!! */
					critical = payload.data[0];
					ASN1_GetNextObject(&sub_item,&payload);
				}

				if (((unsigned short)element.data[0] == (unsigned short)id_ce[0]) && ASN1_CHECK_OBJECT(payload,A1T_PRIMITIVE,A1C_UNIVERSAL,A1UC_OCTETSTRING_TYPE))
				{
					/* decode the elements and ignore the ones that we don't support */
					switch(element.data[2])
					{
						case X520_ID_CE_AUTHORITYKEYIDENTIFIER:			/* Does not need support, but should be supported  (except when is MUST be. Ahhhh!!!!! ) */
							if (ASN1_GetNextObject(&payload,&sub_element) && ASN1_CHECK_OBJECT(sub_element,A1T_CONSTRUCTED,A1C_UNIVERSAL,A1UC_SEQUENCE_TYPE))
							{
								if (ASN1_GetNextObject(&sub_element,&sub_sub_element) && ASN1_CHECK_OBJECT(sub_sub_element,A1T_PRIMITIVE,A1C_CONTEXT_SPECIFIC,0))
								{
								}
								else if (ASN1_GetNextObject(&sub_element,&sub_sub_element) && ASN1_CHECK_OBJECT(sub_sub_element,A1T_PRIMITIVE,A1C_CONTEXT_SPECIFIC,1))
								{
									/* I can't be arsed decoding the rest, its pointless */
								}
								else if (ASN1_GetNextObject(&sub_element,&sub_sub_element) && ASN1_CHECK_OBJECT(sub_sub_element,A1T_PRIMITIVE,A1C_CONTEXT_SPECIFIC,2))
								{
									/* as above */
								}
							}
							break;

						case X520_ID_CE_SUBJECTKEYIDENTIFIER:			/* Does not need support, but should be supported */
							if (ASN1_GetNextObject(&payload,&sub_element) && ASN1_CHECK_OBJECT(sub_element,A1T_PRIMITIVE,A1C_UNIVERSAL,A1UC_OCTETSTRING_TYPE))
							{
								/* we havethe subject key ID */
								// hexDump(sub_element.data,sub_element.length);
							}
							break;

						case X520_ID_CE_BASICCONSTRAINTS:				/* must be supported */
							if (ASN1_GetObject(payload.data,&sub_element) && sub_element.length != 0)
							{
								if (ASN1_GetNextObject(&sub_element,&sub_sub_element) && ASN1_CHECK_OBJECT(sub_sub_element,A1T_PRIMITIVE,A1C_UNIVERSAL,A1UC_BOOLEAN_TYPE))
								{
									/* we have the CA flag */
									certificate->public_key.isCA = sub_sub_element.data[0];
								}
							}
							break;

						case X520_ID_CE_KEYUSAGE:						/* must be supported */
							if (ASN1_GetObject(payload.data,&sub_element) && ASN1_CHECK_OBJECT(sub_element,A1T_PRIMITIVE,A1C_UNIVERSAL,A1UC_BITSTRING_TYPE) )
							{
								/* we have the key usage */
								certificate->public_key.cert_usage = (sub_element.data[1] | (sub_element.data[2] << 8));
							}
							break;

						case X520_ID_CE_CERTIFICATEPOLICIES:			/* must be supported */
								if (critical)
									result = 0;		/* fail is the cert requires this */
								hexDump(sub_item.data,sub_item.length);
							break;

						case X520_ID_CE_SUBJECTALTNAME:					/* must be supported */
								if (critical)
									result = 0;		/* fail is the cert requires this */
								hexDump(sub_item.data,sub_item.length);
							break;

						case X520_ID_CE_NAMECONSTRAINTS:				/* must be supported */
								if (critical)
									result = 0;		/* fail is the cert requires this */
							break;

						case X520_ID_CE_EXTKEYUSAGE:					/* must be supported */
								if (critical)
									result = 0;		/* fail is the cert requires this */
							break;

						case X520_ID_CE_POLICYCONSTRAINTS:				/* must be supported */
								if (critical)
									result = 0;		/* fail is the cert requires this */
							break;

						case X520_ID_CE_INHIBITANYPOLICY:				/* must be supported */		
								if (critical)
									result = 0;		/* fail is the cert requires this */
							break;

						/* none of the following need to be supported */	
						case X520_ID_CE_PRIVATEKEYUSAGEPERIOD:
						case X520_ID_CE_POLICYMAPPINGS:
						case X520_ID_CE_ISSUERALTNAME:
						case X520_ID_CE_SUBJECTDIRECTORYATTRIBUTES:
						case X520_ID_CE_CRLDISTRIBUTIONPOINTS:
						case X520_ID_CE_FRESHESTCRL:
						case X520_ID_CE_CRLNUMBER:
						case X520_ID_CE_ISSUINGDISTRIBUTIONPOINT:
						case X520_ID_CE_DELTACRLINDICATOR:
						case X520_ID_CE_CRLREASONS:
						case X520_ID_CE_CERTIFICATEISSUER:
						case X520_ID_CE_HOLDINSTRUCTIONCODE:
						case X520_ID_CE_INVALIDITYDATE:
							break;
					}
				}
			}
		}
	}
	return result;
}
Ejemplo n.º 18
0
/* Loop until it is explicitly halted or the network is lost, then clean up. */
static int run_loop(struct mosquitto *m) {
	int res;
	long lastMess; 
	for (;;) {
		res = mosquitto_loop(m, 10, 1);

		// No messages have been received withing MESSAGE_WATCHDOG interval
		if (millis() > lastMess + theConfig.messageWatchdogDelay) {
			LOG("=== Message WatchDog ===\n");
			theStats.messageWatchdog++;
			// re-initialise the radio
			initRfm(rfm69);
			// reset watchdog
			lastMess = millis();
		}
		
		if (rfm69->receiveDone()) {
			// record last message received time - to compute radio watchdog
			lastMess = millis();
			theStats.messageReceived++;
			
			// store the received data localy, so they can be overwited
			// This will allow to send ACK immediately after
			uint8_t data[RF69_MAX_DATA_LEN]; // recv/xmit buf, including header & crc bytes
			uint8_t dataLength = rfm69->DATALEN;
			memcpy(data, (void *)rfm69->DATA, dataLength);
			uint8_t theNodeID = rfm69->SENDERID;
			uint8_t targetID = rfm69->TARGETID; // should match _address
			uint8_t PAYLOADLEN = rfm69->PAYLOADLEN;
			uint8_t ACK_REQUESTED = rfm69->ACK_REQUESTED;
			uint8_t ACK_RECEIVED = rfm69->ACK_RECEIVED; // should be polled immediately after sending a packet with ACK request
			int16_t RSSI = rfm69->RSSI; // most accurate RSSI during reception (closest to the reception)

			if (ACK_REQUESTED  && targetID == theConfig.nodeId) {
				// When a node requests an ACK, respond to the ACK
				// but only if the Node ID is correct
				theStats.ackRequested++;
				rfm69->sendACK();
				
				if (theStats.ackCount++%3==0) {
					// and also send a packet requesting an ACK (every 3rd one only)
					// This way both TX/RX NODE functions are tested on 1 end at the GATEWAY

					usleep(3000);  //need this when sending right after reception .. ?
					theStats.messageSent++;
					if (rfm69->sendWithRetry(theNodeID, "ACK TEST", 8)) { // 3 retry, over 200ms delay each
						theStats.ackReceived++;
						LOG("Pinging node %d - ACK - ok!", theNodeID);
					}
					else {
						theStats.ackMissed++;
						LOG("Pinging node %d - ACK - nothing!", theNodeID);
					}
				}
			}//end if radio.ACK_REQESTED
	
			LOG("[%d] to [%d] ", theNodeID, targetID);

			if (dataLength != sizeof(Payload)) {
				LOG("Invalid payload received, not matching Payload struct! %d - %d\r\n", dataLength, sizeof(Payload));
				hexDump(NULL, data, dataLength, 16);		
			} else {
				theData = *(Payload*)data; //assume radio.DATA actually contains our struct and not something else

				//save it for mosquitto:
				sensorNode.nodeID = theData.nodeID;
				sensorNode.sensorID = theData.sensorID;
				sensorNode.var1_usl = theData.var1_usl;
				sensorNode.var2_float = theData.var2_float;
				sensorNode.var3_float = theData.var3_float;
				sensorNode.var4_int = RSSI;

				LOG("Received Node ID = %d Device ID = %d Time = %d  RSSI = %d var2 = %f var3 = %f\n",
					sensorNode.nodeID,
					sensorNode.sensorID,
					sensorNode.var1_usl,
					sensorNode.var4_int,
					sensorNode.var2_float,
					sensorNode.var3_float
				);
				if (sensorNode.nodeID == theNodeID)
					sendMQTT = 1;
				else {
					hexDump(NULL, data, dataLength, 16);
				}
			}  
		} //end if radio.receive

		if (sendMQTT == 1) {
			//send var1_usl
			MQTTSendULong(m, sensorNode.nodeID, sensorNode.sensorID, 1, sensorNode.var1_usl);

			//send var2_float
			MQTTSendFloat(m, sensorNode.nodeID, sensorNode.sensorID, 2, sensorNode.var2_float);

			//send var3_float
			MQTTSendFloat(m, sensorNode.nodeID, sensorNode.sensorID, 3, sensorNode.var3_float);

			//send var4_int, RSSI
			MQTTSendInt(m, sensorNode.nodeID, sensorNode.sensorID, 4, sensorNode.var4_int);

			sendMQTT = 0;
		}//end if sendMQTT
	}

	mosquitto_destroy(m);
	(void)mosquitto_lib_cleanup();

	if (res == MOSQ_ERR_SUCCESS) {
		return 0;
	} else {
		return 1;
	}
}
Ejemplo n.º 19
0
int main(int argc, char **argv)
{
    int i, rc;
    char buffer[BUFLEN];
    uint8_t arp[sizeof(struct ethhdr) + sizeof(struct arp_hdr)];

    if(argc != 5)
    {
        fprintf(stderr, "Usage: %s <interface> <listen-port> <remote-host> <remote-port>\n\n", argv[0]);
        return(1);
    }

    memset(fd_udp_port, 0, sizeof(fd_udp_port));
    
    int port = atoi(argv[2]);
    char *iface_out = argv[1];
    char *rhost = argv[3];
    int rport = atoi(argv[4]);

    int sock_udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    int sock_raw_recv = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
    int sock_raw_send = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
    setsockopt(sock_raw_recv, SOL_SOCKET, SO_BINDTODEVICE, iface_out, 4);
    setsockopt(sock_raw_send, SOL_SOCKET, SO_BINDTODEVICE, iface_out, 4);
    int on = 1;
    setsockopt(sock_raw_send, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on));

    ssize_t recsize;
    struct sockaddr_in udp_listen_addr, udp_client_addr, other_addr;
    socklen_t slen = sizeof(struct sockaddr_in);
    socklen_t udp_client_addr_size = slen;
    udp_listen_addr.sin_family = AF_INET;
    udp_listen_addr.sin_addr.s_addr = INADDR_ANY;
    if(port == 0)
    {
        srand(time(NULL));
        do
        {
            port = 6001 + rand() % 22000; // random port 6001-28000
            udp_listen_addr.sin_port = htons(port);

            rc = bind_public(sock_udp,(struct sockaddr *)&udp_listen_addr, sizeof(udp_listen_addr));
        } while(rc == -1);
    }
    else
    {
        udp_listen_addr.sin_port = htons(port);
        rc = bind_public(sock_udp,(struct sockaddr *)&udp_listen_addr, sizeof(udp_listen_addr));
    }

    if(rc == -1)
    {
        perror("error bind failed");
        close(sock_udp);
        fprintf(stderr, "(is another tunnel or socat process already running?)\n");
        exit(EXIT_FAILURE);
    }
    DEBUG_PRINT("Listening on port %i...\n", port);

    // Find interface index from interface name and store index in
    // struct sockaddr_ll device, which will be used as an argument of sendto().
    struct sockaddr_ll device;
    memset(&device, 0, sizeof(struct sockaddr_ll));
    device.sll_family = AF_PACKET;
    device.sll_halen = 6;
    if((device.sll_ifindex = if_nametoindex(iface_out)) == 0) {
      perror("if_nametoindex() failed to obtain interface index ");
      exit(EXIT_FAILURE);
    }
    DEBUG_PRINT("Index for interface %s is %i\n", iface_out, device.sll_ifindex);

    struct ifreq ifr;
    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name, iface_out, IFNAMSIZ-1);

    // get MAC address of iface_out
    if(ioctl(sock_raw_send, SIOCGIFHWADDR, &ifr) < 0)
    {
        perror("ioctl() failed to get source MAC address ");
        exit(EXIT_FAILURE);
    }
    uint8_t if_raw_mac[6];
    memcpy(if_raw_mac, ifr.ifr_hwaddr.sa_data, 6 * sizeof(uint8_t));
    memcpy(device.sll_addr, ifr.ifr_hwaddr.sa_data, 6 * sizeof (uint8_t));
    DEBUG_PRINT("MAC address for interface %s is ", iface_out);
    for(i=0; i<5; i++) {
        DEBUG_PRINT("%02x:", if_raw_mac[i]);
    }
    DEBUG_PRINT("%02x\n", if_raw_mac[5]);

    // get IP address address of iface_out
    if(ioctl(sock_raw_send, SIOCGIFADDR, &ifr) < 0)
    {
        perror("ioctl() failed to get interface IP address");
        exit(EXIT_FAILURE);
    }
    struct in_addr if_raw_addr = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
    printf("TUNIP=%s \n",inet_ntoa(if_raw_addr));
    DEBUG_PRINT("Rewriting IP source address to %s\n", inet_ntoa(if_raw_addr));

    // send gratuitous ARP
    DEBUG_PRINT("Sending gratuitous ARP to map ");
    for(i=0; i<5; i++) {
        DEBUG_PRINT("%02x:", if_raw_mac[i]);
    }
    DEBUG_PRINT("%02x to %s\n", if_raw_mac[5], inet_ntoa(if_raw_addr));
    memset(arp, 0, sizeof(arp));
    struct ethhdr *arp_ethhdr = (void *)arp;
    struct arp_hdr *arp_arphdr = (void *)arp + sizeof(struct ethhdr);
    arp_arphdr->htype = htons(1);
    arp_arphdr->ptype = htons(ETH_P_IP);
    arp_arphdr->hlen = 6;
    arp_arphdr->plen = 4;
    arp_arphdr->opcode = htons(2); // 1 = ARP request, 2 = ARP reply
    memcpy(arp_arphdr->sender_mac, if_raw_mac, 6 * sizeof(uint8_t));
    memcpy(arp_arphdr->sender_ip, &if_raw_addr.s_addr, 4 * sizeof(uint8_t));
    memcpy(arp_arphdr->target_mac, if_raw_mac, 6 * sizeof(uint8_t));
    memcpy(arp_arphdr->target_ip, &if_raw_addr.s_addr, 4 * sizeof(uint8_t));
    memcpy(arp_ethhdr->h_source, if_raw_mac, 6 * sizeof (uint8_t));
    memset(arp_ethhdr->h_dest, 0xff, 6 * sizeof (uint8_t));
    arp_ethhdr->h_proto = htons(ETH_P_ARP);
    int bytes_sent = sendto(sock_raw_recv, arp, sizeof(arp), 0,(struct sockaddr*)&device, sizeof(device));
    if(bytes_sent != sizeof(arp))
    {
        perror("sendto(arp) failed");
    }

    struct sockaddr_in server,mapped;
    struct hostent *hostinfo;

    hostinfo = gethostbyname(stunserver);
    if (!hostinfo) {
        fprintf(stderr, "Error resolving host %s\n", stunserver);
        return -1;
    }
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr = *(struct in_addr*) hostinfo->h_addr;
    server.sin_port = htons(stunport);

    int res = stun_request(sock_udp, &server, NULL, &mapped);
    if (!res && (mapped.sin_addr.s_addr != htonl(INADDR_ANY)))
    {
        printf("CONNECT=%s:",inet_ntoa(mapped.sin_addr));
        printf("%d\n",htons(mapped.sin_port));
    }
    DEBUG_PRINT("Sending \"OPEN!\" packet to remote host (for UDP hole punching)\n");

    hostinfo = gethostbyname(rhost);
    if(!hostinfo) {
        fprintf(stderr, "Error resolving remote-host\n");
        return -1;
    }
    memset(&udp_client_addr, 0, sizeof(udp_client_addr));
    udp_client_addr.sin_family = AF_INET;
    udp_client_addr.sin_addr = *(struct in_addr*) hostinfo->h_addr;
    udp_client_addr.sin_port = htons(rport);
    strcpy(buffer, "OPEN!");
    sendto(sock_udp, buffer, 5, 0,(struct sockaddr*)&udp_client_addr, udp_client_addr_size);

    DEBUG_PRINT("Waiting for connection from remote host...\n");
    recsize = recvfrom(sock_udp, (void *)buffer, BUFLEN, 0, (struct sockaddr *)&udp_client_addr, &udp_client_addr_size);
    if(recsize == -1)
    {
        perror("recv error");
        close(sock_udp);
        close(sock_raw_recv);
        close(sock_raw_send);
        exit(EXIT_FAILURE);
    }
    DEBUG_PRINT("Received packet from %s:%d\n", inet_ntoa(udp_client_addr.sin_addr), ntohs(udp_client_addr.sin_port));

    fd_set rset;
    FD_ZERO(&rset);
    maxfd = sock_raw_send;
    int eof_socket = 0;
    while(!eof_socket)
    {
        int res = -1;
        FD_SET(sock_udp, &rset);
        FD_SET(sock_raw_recv, &rset);
        FD_SET(sock_raw_send, &rset);
        int sock_fake;
        for(sock_fake = maxfd + 1; sock_fake <= maxfd; sock_fake++)
        {
            FD_SET(sock_fake, &rset);
        }
        res = select(maxfd + 1, &rset, 0, 0, 0);
        if(res < 0) {
            fprintf(stderr, "select failed!\n");
            exit(EXIT_FAILURE);
        }
        if(FD_ISSET(sock_raw_recv, &rset))
        {
            slen = sizeof(struct sockaddr_in);
            recsize = recvfrom(sock_raw_recv, (void *)buffer, BUFLEN, 0, (struct sockaddr *)&other_addr, &slen);
            if(recsize > 0)
            {
                struct ethhdr *eth = (struct ethhdr *)buffer;
                if(ntohs(eth->h_proto) == ETH_P_ARP)
                {
                    struct arp_hdr *packet = (void *)buffer + sizeof(struct ethhdr);
                    if(ntohs(packet->opcode) == 1) // ARP request
                    {
                        /* printf("Received ARP request from RAW socket\n"); */
                        /* printf("target_ip: %s\n", inet_ntoa(*(struct in_addr *)&packet->target_ip)); */
                        if(0 == memcmp(&packet->target_ip, &if_raw_addr.s_addr, 4 * sizeof(uint8_t))) // our IP
                        {
                            DEBUG_PRINT("Received ARP request for our IP from RAW socket, replying...\n");
                            // send ARP reply back to the sender of the ARP request
                            memcpy(arp_ethhdr->h_dest, packet->sender_mac, 6 * sizeof (uint8_t));
                            int bytes_sent = sendto(sock_raw_recv, arp, sizeof(arp), 0,(struct sockaddr*)&device, sizeof(device));
                            if(bytes_sent != sizeof(arp))
                            {
                                perror("sendto(arp) failed");
                            }
                        }
                    }
                }
                else if(ntohs(eth->h_proto) == ETH_P_IP)
                {
                    struct iphdr *packet = (void *)buffer + sizeof(struct ethhdr);
                    if(packet->daddr == if_raw_addr.s_addr)
                    {
                        DEBUG_PRINT("Received IP packet from RAW socket: ");
                        DEBUG_PRINT("%s -> ", inet_ntoa(*(struct in_addr *)&packet->saddr));
                        DEBUG_PRINT("%s\n", inet_ntoa(*(struct in_addr *)&packet->daddr));

                        int skip = 0;

                        if(packet->protocol == IPPROTO_ICMP)
                        {
                            struct icmphdr *data = (void *)buffer + sizeof(struct ethhdr) + sizeof(struct iphdr);
                            if(data->type == ICMP_ECHOREPLY)
                            {
                                DEBUG_PRINT("Protocol: ICMP, echo reply, id: %x\n", data->un.echo.id);
                            }
                            else
                            {
                                DEBUG_PRINT("Protocol: ICMP, type: %d, code: %d\n", data->type, data->code);
                            }
                        }
                        else if(packet->protocol == IPPROTO_TCP)
                        {
                            struct tcphdr *data = (void *)packet + sizeof(struct iphdr);
                            DEBUG_PRINT("Protocol: TCP, sport: %d, dport: %d\n", htons(data->source), htons(data->dest));

                            DEBUG_PRINT("If we had a TCP stack we'd have to feed this packet into it, but now we're skipping it.\n");
                            skip = 1;
                        }
                        else if(packet->protocol == IPPROTO_UDP)
                        {
                            struct udphdr *data = (void *)packet + sizeof(struct iphdr);
                            DEBUG_PRINT("Protocol: UDP, sport: %d, dport: %d\n", htons(data->source), htons(data->dest));
                            if(packet->saddr == udp_client_addr.sin_addr.s_addr)
                            {
                                if(htons(data->source) == rport && htons(data->dest) == port)
                                {
                                    DEBUG_PRINT("Skipping packet, this is our own UDP tunnel!\n");
                                    skip = 1;
                                }
                            }
                        }
                        else
                        {
                            DEBUG_PRINT("Unknown protocol: %d\n", packet->protocol);
                        }
                        if(skip == 0)
                        {
                            int bytes_sent = sendto(sock_udp, packet, recsize-sizeof(struct ethhdr), 0,(struct sockaddr*)&udp_client_addr, udp_client_addr_size);
                            if(bytes_sent != recsize-sizeof(struct ethhdr))
                            {
                                perror("sendto() failed");
                                DEBUG_PRINT("tried sending to %s:%d\n", inet_ntoa(udp_client_addr.sin_addr), ntohs(udp_client_addr.sin_port));
                                hexDump("packet", packet, recsize-sizeof(struct ethhdr));
                                hexDump("udp_client_addr", &udp_client_addr, udp_client_addr_size);
                            }
                        }
                    }
                }
            }
        }
        if(FD_ISSET(sock_udp, &rset))
        {
            slen = sizeof(struct sockaddr_in);
            recsize = recvfrom(sock_udp, (void *)buffer, BUFLEN, 0, (struct sockaddr *)&other_addr, &slen);
            if(recsize == 4 && strcmp(buffer, "EXIT") == 0)
            {
                eof_socket = 1;
            }
            else if(recsize > 0)
            {
                DEBUG_PRINT("Received packet from UDP socket\n");

                struct iphdr *packet = (struct iphdr *)buffer;
                struct in_addr in_addr_source, in_addr_dest;
                in_addr_source.s_addr = packet->saddr;
                in_addr_dest.s_addr = packet->daddr;
                struct sockaddr_in dest_addr;
                dest_addr.sin_family = AF_INET;
                dest_addr.sin_addr = in_addr_dest;
                DEBUG_PRINT("saddr: %s ", inet_ntoa(in_addr_source));
                DEBUG_PRINT("daddr: %s\n", inet_ntoa(in_addr_dest));

                /* hexDump("buffer", &buffer, recsize); */

                if(packet->protocol == IPPROTO_ICMP)
                {
                    struct icmphdr *data = (void *)buffer + sizeof(struct iphdr);

                    DEBUG_PRINT("Protocol: ICMP, id: %x\n", data->un.echo.id);

                    if(-1 == sendto(sock_raw_send, buffer, recsize, 0,(struct sockaddr*)&dest_addr, sizeof(dest_addr)))
                    {
                        perror("sendto() failed");
                    }
                }
                else if(packet->protocol == IPPROTO_TCP)
                {
                    // TCP should be handled by the other tunnel endpoint via tun2socks and not actually be sent through the UDP tunnel...

                    struct tcphdr *data = (void *)buffer + sizeof(struct iphdr);

                    DEBUG_PRINT("Protocol: TCP, sport: %d, dport: %d - what is this packet doing here?\n", htons(data->source), htons(data->dest));
                }
                else if(packet->protocol == IPPROTO_UDP)
                {
                    struct udphdr *data = (void *)buffer + sizeof(struct iphdr);

                    DEBUG_PRINT("Protocol: UDP, sport: %d, dport: %d\n", htons(data->source), htons(data->dest));

                    // open and bind a UDP socket on the source port so the kernel doesn't send ICMP unreachable packets
                    int sock_fake_udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
                    struct sockaddr_in fake_addr;
                    fake_addr.sin_family = AF_INET;
                    fake_addr.sin_addr.s_addr = INADDR_ANY;
                    fake_addr.sin_port = data->source;
                    if(-1 == bind_public(sock_fake_udp,(struct sockaddr *)&fake_addr, sizeof(struct sockaddr_in)))
                    {
                        perror("bind() failed");
                    }
                    fd_udp_port[sock_fake_udp] = htons(data->dest);
                    maxfd = sock_fake_udp;

                    if(-1 == sendto(sock_raw_send, buffer, recsize, 0,(struct sockaddr*)&dest_addr, sizeof(dest_addr)))
                    {
                        perror("sendto() failed");
                    }
                }
                else
                {
                    if(-1 == sendto(sock_raw_send, buffer, recsize, 0,(struct sockaddr*)&dest_addr, sizeof(dest_addr)))
                    {
                        perror("sendto() failed");
                    }
                }
            }
            else eof_socket = 1;
        }
        for(sock_fake = sock_raw_send + 1; sock_fake <= maxfd; sock_fake++)
        {
            if(FD_ISSET(sock_fake, &rset))
            {
                slen = sizeof(struct sockaddr_in);
                // just empty the socket's recv buffer and discard the data,
                // it is read and forwarded by the RAW socket sock_raw_recv
                recsize = recvfrom(sock_fake, (void *)buffer, BUFLEN, 0, (struct sockaddr *)&other_addr, &slen);
            }
        }
    }
    return(0);
}
Ejemplo n.º 20
0
//------------------------------------------
void process_packet(u_char *useless, const struct pcap_pkthdr *pkthdr,
                    const u_char *packet) {

  // Test to see if we've been told to stop processing packets, e.g. because of signal

  if (process_packets == false)
  {
    pcap_breakloop(pPCAPDescriptor);
  }

  // update stats

  ++(stats.packets_processed);

  // check packet capture size
  if (pkthdr->caplen < SIZE_ETHERNET)
  {
    syslog(LOG_WARNING, "Packet capture length was smaller than ethernet header");
    return;
  }

  // declare pointers to packet headers

  const struct sniff_ethernet *ethernet; // The ethernet header [1]
  const struct sniff_ip *ip;             // The IP header

  // define ethernet header

  ethernet = (struct sniff_ethernet *)(packet);

  //	printf("\tMAC src: %s\n", ether_ntoa((const struct
  // ether_addr*)(ethernet->ether_shost)));
  //	printf("\tMAC dst: %s\n", ether_ntoa((const struct
  // ether_addr*)(ethernet->ether_dhost)));

  switch (ntohs(ethernet->ether_type))
  {
    case 0x0800:
      // IPv4
      ++(stats.ipv4_packets);
      break;
    case 0x0806:
      // ARP
      ++(stats.arp_packets);
      return;
      break;
    case 0x86dd:
      // ipv6_packets
      ++(stats.ipv6_packets);
      return;
      break;
    case 0x888e:
      // 802.1x Auth Packets
      ++(stats.e02_auth_packets);
      return;
      break;
    default:
      ++(stats.other_packets);
      hexDump("Other Packet", (void*)packet, pkthdr->caplen);
      return;
      break;
  }

  // check packet capture size
  if (pkthdr->caplen < (sizeof(struct sniff_ip) + SIZE_ETHERNET))
  {
    syslog(LOG_WARNING, "Packet capture length was smaller than ethernet and IP header");
    return;
  }

  // define/compute ipv4 header offset

  ip = (struct sniff_ip *)(packet + SIZE_ETHERNET);

  int size_ip;
  size_ip = IP_HL(ip) * 4;

  if (size_ip < 20) {
    syslog(LOG_WARNING, "Invalid IP header length: %u bytes\n", size_ip);
    return;
  }

  // calculate the 'key' based on the 5 tuple used for matching sessions
  // together

  uint32_t key =
      ntohl(*(uint32_t *)&(ip->ip_dst)) ^ ntohl(*(uint32_t *)&(ip->ip_src));

  // determine protocol

  switch (ip->ip_p) {

  case IPPROTO_TCP:
    {

      ++(stats.ipv4_tcp_packets);

      struct sniff_tcp *tcp;

      tcp = (struct sniff_tcp *)(packet + SIZE_ETHERNET + size_ip);

      struct portmanteau_session_header *hdr;

      hdr = calloc(1, sizeof(struct portmanteau_session_header));

      if (hdr != NULL) {

        // increment allocated memory stats
        stats.memory_allocated += sizeof(struct portmanteau_session_header);

        hdr->ip_src_adr = *(uint32_t *)&(ip->ip_src);
        // stored in network order
        hdr->ip_dst_adr = *(uint32_t *)&(ip->ip_dst);
        // stored in network order
        hdr->key = key;
        hdr->next_proto = ip->ip_p;
        hdr->packet_number = stats.packets_processed;
        hdr->src_port = ntohs(tcp->th_sport);
        // stored in host order
        hdr->dst_port = ntohs(tcp->th_dport); // stored in host order

        // examine port number to decide if client to server, etc
        // this is crudely based on the fact that ephemeral port numbers are usually larger

        if ((hdr->dst_port > hdr->src_port) && (hdr->dst_port >= EPHEMERAL_PORT_START))
        {
          ++(stats.server_to_client);
        }

        if ((hdr->src_port > hdr->dst_port) && (hdr->src_port >= EPHEMERAL_PORT_START))
        {
          ++(stats.client_to_server);
        }

        int size_tcp;
        u_char *payload; // Packet payload
        int size_payload;

        size_tcp = TH_OFF(tcp) * 4;

        if (size_tcp < 20) {
          syslog(LOG_WARNING, "Invalid TCP header length: %u bytes\n", size_tcp);
          return;
        }

        // define/compute tcp payload (segment) offset

        payload = (u_char *)(tcp) + size_tcp;

        // compute tcp payload (segment) size

        size_payload = ntohs(ip->ip_len) - (size_ip + size_tcp);

        // printf("TCP payload size: %u\n", size_payload);

        hdr->payload_size = size_payload;

        if (size_payload > 0) {

          // allocate the memory, and store the packet
          hdr->payload = calloc(1, size_payload);

          if (hdr->payload != NULL)
          {
            stats.memory_allocated += hdr->payload_size;
            memcpy(hdr->payload, payload, hdr->payload_size);
          }
        }

        // analyse packet against fingerprints
        analyse(hdr);

        // after analysis, free the memory
        free(hdr->payload);
        stats.memory_allocated -= hdr->payload_size;
        free(hdr);
        stats.memory_allocated -= sizeof(struct portmanteau_session_header);

      }

      break;
    }

      case IPPROTO_UDP:
        ++(stats.ipv4_udp_packets);
        break;

      case IPPROTO_ICMP:
        ++(stats.ipv4_icmp_packets);
        break;

      case IPPROTO_IP:
        ++(stats.ipv4_ip_packets);
        break;

      case IPPROTO_IGMP:
        ++(stats.ipv4_igmp_packets);
        break;

      default:
        ++(stats.ipv4_other_packets);
        hexDump("IPv4 Other Packet", (void*)packet, pkthdr->caplen);
        break;

  }
}
Ejemplo n.º 21
0
/*---------------------------------------------------------------------------*/
int main(int argc, char**argv)
{
	int i;
	int fd = 0;
	uint16_t trial = 0;
	char* portPath = NULL;
	char* rx_addressString = NULL;
	char* tx_addressString = NULL;

	printf("> Simple message listener for tea-bootloader compatible nodes\n");        
	
	/*-----------------------------------------------------------------------*/
	
	if(argc == 4)
	{
		portPath = argv[1];		
		rx_addressString = argv[2];
		sscanf(rx_addressString,"%X:%X:%X:%X:%X",rx_addressBuffer,rx_addressBuffer+1,rx_addressBuffer+2,rx_addressBuffer+3,rx_addressBuffer+4);
		tx_addressString = argv[3];
		sscanf(tx_addressString,"%X:%X:%X:%X:%X",tx_addressBuffer,tx_addressBuffer+1,tx_addressBuffer+2,tx_addressBuffer+3,tx_addressBuffer+4);
	}
	else
	{
		printf("> Argument parsing error!\n");
		printf("> Usage: [port path] [dongle RX address] [node RX address]\n");
		printf("> Example: ./main /dev/tty.usbserial-A900cbrd 0xE7:0xE7:0xE7:0xE7:0x00 0xD7:0xD7:0xD7:0xD7:0xD7\n");
		return 0;
	}			

	/*-----------------------------------------------------------------------*/	   

    fd = serialport_init(portPath,115200,'n');

    if(fd < 0)
    {
        printf("[err]: Connection error.\n");
        return 0;
    }
    else
   	{
        printf("> Conection OK.\n");
        serialport_flush(fd);
        printf("> Serial port flush OK.\n");   

        if(loopbackTest(fd) != 0)
        {
        	printf("> Loopback test failed!\r\n");
        	return 0;
        }
        else
        {        	
        	uint8_t version = getVersion(fd);
        	printf("> Dongle version: %d.%d\r\n",(version>>4),(version&0x0F));
        }                    
    }   

    printf("> Setting the TX address ...\n");
    setTXAddress(fd,tx_addressBuffer);

    printf("> Setting the RX address ...\n");
    setRXAddress(fd,rx_addressBuffer);

    while(1)
    {
    	uint8_t thisBuffer[1024];
    	char sendBuffer[256];
    	uint8_t len;
    	int temp;
    	float realval;
    	if(getRxFifoCount(fd))
    	{
			len = getRxFifoCount(fd);
			printf("> ---------------------------------------------------------------------------\n");
			printf("> New message!\n");
			printf("> Length: %d\n",len);
			pullDataFromFifo(fd,len,thisBuffer);

			hexDump("> Dump",thisBuffer,len);			

			temp = (thisBuffer[0]<<8)+thisBuffer[1];
			realval  = ((float)temp * 1100.0) / 1024.0;              
			realval -= 500;
			realval /= 10.0;

			printf("> Raw: %d\n",temp);
			printf("> Readout: %f\n",realval);
			sprintf(sendBuffer,"./phant_client.rb %f",realval);
			system(sendBuffer);
			printf("> Phant.io send process done.\n");
    	}
    }


}
Ejemplo n.º 22
0
static BOOL
initCrypt()
{
    BYTE	buffer[ 1024 ];
    DWORD	size, flags;

    if ( ! CryptAcquireContext( &provider, NULL, NULL, ProvType, CRYPT_VERIFYCONTEXT ) )
    {
	fprintf( stderr, "CryptAcquireContext() failed: 0x%x\n", GetLastError() );
	return( FALSE );
    }

    if ( ! CryptGenKey( provider, XchgKeyType, XchgKeyFlags, &xchgKey ) )
    {
	fprintf( stderr, "CryptGenKey() failed: 0x%x\n", GetLastError() );
	return( FALSE );
    }

    for( flags = CRYPT_FIRST; ; flags = CRYPT_NEXT )
    {
	PROV_ENUMALGS_EX *info = (PROV_ENUMALGS_EX *)buffer;

	size = sizeof( buffer );

	if ( ! CryptGetProvParam( provider, PP_ENUMALGS_EX, buffer, &size, flags ) )
	{
	    DWORD status = GetLastError();

	    if ( status == ERROR_NO_MORE_ITEMS )  break;
	    fprintf( stderr, "CryptGetProvParam() failed: 0x%x\n", GetLastError() );
	    return( FALSE );
	}

	switch( info->aiAlgid )
	{
	case CALG_RSA_KEYX :	rsaMaxKey = max( rsaMaxKey, info->dwMaxLen );	break;
	case CALG_AES_128 :
	case CALG_AES_192 :
	case CALG_AES_256 :	aesMaxKey = max( aesMaxKey, info->dwMaxLen );	break;
	}
    }

    if ( verbose )
    {
	struct pkb
	{
	    PUBLICKEYSTRUC	hdr;
	    RSAPUBKEY		rsa;
	    BYTE		mod[1];
	}	*rsaKey= (struct pkb *)buffer;

	printf( "RSA Max Key Length: %d\n", rsaMaxKey );
	printf( "AES Max Key Length: %d\n", aesMaxKey );

	if ( ! CryptExportKey( xchgKey, 0, PUBLICKEYBLOB, 0, NULL, &size ) )
	{
	     fprintf( stderr, "CryptExportKey() [1] failed: 0x%x\n", GetLastError() );
	     return( FALSE );
	}

	if ( size > sizeof( buffer ) )
	{
	    fprintf( stderr, "CryptExportKey() requires %d bytes\n", size );
	    return( FALSE );
	}

	size = sizeof( buffer );

	if ( ! CryptExportKey( xchgKey, 0, PUBLICKEYBLOB, 0, (BYTE *)rsaKey, &size ) )
	{
	     fprintf( stderr, "CryptExportKey() [2] failed: 0x%x\n", GetLastError() );
	     return( FALSE );
	}

	printf( "Xchg Exp: %d\n", rsaKey->rsa.pubexp );
	printf( "Xchg Mod: \n" );
	hexDump( rsaKey->rsa.bitlen / 8, rsaKey->mod );
    }

    if ( rsaMaxKey < 1024  ||  aesMaxKey < 128 )
    {
	fprintf( stderr, "Invalid minimum key length\n" );
	return( FALSE );
    }

    return( TRUE );
}
Ejemplo n.º 23
0
static BOOL
decodeSK( BOOL aes256, DWORD keylen, BYTE *keybuf )
{
    BYTE	buffer[ 1024 ];
    DWORD	i, size, length;

    struct skb
    {
	PUBLICKEYSTRUC	hdr;
	ALG_ID		algId;
	BYTE		key[1];
    }		*expKey = (struct skb *)buffer;

    struct ptkb
    {
	PUBLICKEYSTRUC	hdr;
	DWORD		keysize;
	BYTE		key[1];
    }		*txtKey = (struct ptkb *)buffer;

    length = (expKey->key - buffer) + keylen;

    if ( length > sizeof( buffer ) )
    {
	fprintf( stderr, "CryptImportKey() requires %d bytes\n", length );
	return( FALSE );
    }

    expKey->hdr.bType = SIMPLEBLOB;
    expKey->hdr.bVersion = CUR_BLOB_VERSION;
    expKey->hdr.reserved = 0;
    expKey->hdr.aiKeyAlg = aes256 ? SessKey256 : SessKey128;
    expKey->algId = XchgKeyType;

    /*
    ** NOTE: it appears that the encoded key is byte swapped compared
    ** to external standards.  There is a cryptic reference to a
    ** ReverseMemCopy() function in the RSA/SChannel server master
    ** key creation example.  Also, the internal RSA modulus is
    ** byte swapped compared to the X509 encoding.  This swap is
    ** required to interoperate with JavaSSE.
    */
    for( i = 0; i < keylen; i++ )
	expKey->key[i] = keybuf[ keylen - i - 1 ];

    if ( ! CryptImportKey( provider, (BYTE *)expKey, length, xchgKey, CRYPT_EXPORTABLE, &sessKey ) )
    {
	fprintf( stderr, "CryptImportKey() failed: 0x%x\n", GetLastError() );
	return( FALSE );
    }

    if ( ! CryptSetKeyParam( sessKey, KP_MODE, (BYTE *)&sessKeyMode, 0 ) )
    {
	fprintf( stderr, "CryptSetKeyParam() MODE failed: 0x%x\n", GetLastError() );
	return( 0 );
    }

    if ( ! CryptSetKeyParam( sessKey, KP_PADDING, (BYTE *)&sessKeyPadding, 0 ) )
    {
	fprintf( stderr, "CryptSetKeyParam() PADDING failed: 0x%x\n", GetLastError() );
	return( 0 );
    }

    if ( sessKeyMode == CRYPT_MODE_CBC )
    {
	size = sizeof( length );

	if ( ! CryptGetKeyParam( sessKey, KP_BLOCKLEN, (BYTE *)&length, &size, 0 ) )
	{
	    fprintf( stderr, "CryptGetKeyParam() BLOCKLEN failed: 0x%x\n", GetLastError() );
	    exit( 1 );
        }

	length /= 8;	/* Bits -> bytes */
	for( i = 0; i < length; i++ )  buffer[i] = 0;
	
	if ( ! CryptSetKeyParam( sessKey, KP_IV, buffer, 0 ) )
	{
	    fprintf( stderr, "CryptSetKeyParam() PADDING failed: 0x%x\n", GetLastError() );
	    return( 0 );
	}
    }

    if ( verbose )
    {
	if ( ! CryptExportKey( sessKey, 0, PLAINTEXTKEYBLOB, 0, NULL, &size ) )
	{
	    fprintf( stderr, "CryptExportKey() [1] failed: 0x%x\n", GetLastError() );
	    return( FALSE );
	}

	if ( size > sizeof( buffer ) )
	{
	    fprintf( stderr, "CryptExportKey() requires %d bytes\n", size );
	    return( FALSE );
	}

	length = sizeof( buffer );

	if ( ! CryptExportKey( sessKey, 0, PLAINTEXTKEYBLOB, 0, (BYTE *)txtKey, &length ) )
	{
	    fprintf( stderr, "CryptExportKey() [2] failed: 0x%x\n", GetLastError() );
	    return( FALSE );
	}

	printf( "Sess Key: \n" );
	hexDump( txtKey->keysize, txtKey->key );
	keyInfo( sessKey );
    }

    return( TRUE );
}
Ejemplo n.º 24
0
static void handleCommands(machine_6502 *machine, Bit16 *breaks, int *bpi){
  int c;
  Bit16 start;
  Bit16 end;
  Bit16 numbytes;
  Bool hasSecond;
  fprintf(stdout,"- ");
  c = getchar();
  switch(c){
  case 'a':
    {
      int max = 255;
      char *filename = calloc(max,sizeof(char));
      FILE *out;
      if (filename){
	getfilename(filename,max);
	if (filename[0]){
	  out = fopen(filename, "w");
	  if (out != NULL){
	    disassemble(machine,out);
	    fclose(out);
	  }
	  else {
	    fprintf(stderr,"Could not open file: %s",filename);
	  }
	}
	free(filename);
      }
      else{
	fprintf(stderr,"Could note get memory for the file name.\n");
      }
    }
    return;
  case 'b': /* set a break point */
    {
      Bit16 bp;
      if (*bpi == MAX_BREAK)
	fprintf(stderr,"To many break points.\n");
      else{
	bp = getAddress(&hasSecond);
	breaks[(*bpi)++] = bp;
      }
    }
    return;
  case 'c':{
    getchar(); /* eat the return */
    while(1){
      int i = 0;
      while(i < *bpi){
	if (machine->regPC == breaks[i++])
	  return;
      }
      next_eval(machine,2);
      trace(machine, stdout);
      if (!machine->codeRunning) return;
    }
  }      
  case 'n': 
    getchar(); /* eat the return */
    next_eval(machine,2);
    trace(machine, stdout);
    return;
  case 'd': /* dump the memory address */
    start = getAddress(&hasSecond);
    if (hasSecond){
      end = getAddress(&hasSecond);
      numbytes = abs(start - end);
      if (hasSecond){
	fprintf(stderr,"Only a starting and ending address are allowed.\n");
      }
    }
    else{
      numbytes = 80;
    }
    hexDump(machine,start,numbytes,stdout);
    break;
  case 'p': /* save the program to a file */
    {
      fprintf(stderr,"Disabled for now\n");
      /* int max = 255; */
      /* char *filename = calloc(max,sizeof(char)); */
      /* if (filename){ */
      /* 	getfilename(filename,max); */
      /* 	if (filename[0]){ */
      /* 	  save_program(machine,filename); */
      /* 	} */
      /* 	free(filename); */
      /* } */
      /* else { */
      /* 	fprintf(stderr,"Could not get memory for the file name\n"); */
      /* } */
    }
    break;
  case 'q':
    exit(0);
    break;
  case '?':
    help();
    getchar();
    break;
  default:
    fprintf(stderr,"Invalid command %c\n",c);
    help();
  }
}
Ejemplo n.º 25
0
int larp_reply_pkt(struct arphdr *ar_hdr, struct sockaddr_ll *recv_addr)
{
    int send_sockfd;
    int i, send_bytes, frame_length;
    uint32_t ipaddr_n32;
    //char ipaddr_p[INET_ADDRSTRLEN]; /* to print IP address in presentation format */
    struct sockaddr_ll send_addr;
    struct arphdr send_arhdr; /* standard ARP header fields */
    struct tlv_type_len type_len; /* variable of type-len struct */
    struct label_stack *l_stack = (struct label_stack *) malloc(label_count * sizeof(struct label_stack)); /* For label stack */
    struct attr_tlv a_tlv; /* For Attributes TLV */
    char if_name[IFNAMSIZ];
    uint32_t metric_val;
    unsigned char *s_haddr = allocate_ustrmem (6);
    /*create a RAW PF_PACKET socket for sending out the reply*/
    send_sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ARP));
    if (send_sockfd < 0) { /* socket function returns negative value on error */
        printf("Sending socket creation failed\n");
        exit(1);
    }
    uint8_t *buffer = allocate_ustrmem (IP_MAXPACKET);
    /* Making the buffer all zeros */
    memset(buffer, 0, ETH_FRAME_LEN);
    /* Get the local interface MAC address based on the received interface index*/
    get_mac (recv_addr->sll_ifindex, s_haddr);
    /*zeroing out the struct sockaddr_ll structure*/
    memset(&send_addr, 0, sizeof(struct sockaddr_ll));
    /* Fill in the values for struct sockaddr_ll structure*/

    send_addr.sll_family = PF_PACKET;
    send_addr.sll_protocol = htons(ETH_P_ARP);
    send_addr.sll_ifindex = recv_addr->sll_ifindex;
    send_addr.sll_halen = ETH_ALEN; /*6 bytes for Mac address */
    /* filling target MAC address from source MAC field of received LARP req */
    send_addr.sll_addr[0] = ar_hdr->ar_sha[0];
    send_addr.sll_addr[1] = ar_hdr->ar_sha[1];
    send_addr.sll_addr[2] = ar_hdr->ar_sha[2];
    send_addr.sll_addr[3] = ar_hdr->ar_sha[3];
    send_addr.sll_addr[4] = ar_hdr->ar_sha[4];
    send_addr.sll_addr[5] = ar_hdr->ar_sha[5];
    /* Not used */
    send_addr.sll_addr[6] = 0x00;
    send_addr.sll_addr[7] = 0x00;
#if 0
    for (i=0; i<5; i++)
        printf("%02x:", s_haddr[i]);
    printf("%02x\n", s_haddr[i]);
#endif

    /* Start filling the buffer starting with Ethernet header */

    /* Fill in ethernet header*/
    memcpy(buffer, ar_hdr->ar_sha, ETH_ALEN * sizeof(uint8_t)); /* destination MAC*/
    memcpy(buffer + ETH_ALEN, s_haddr, ETH_ALEN * sizeof(uint8_t)); /* source MAC */
    /* Fill ETH_TYPE = ETH_P_ARP for ARP */
    buffer[12] = ETH_P_ARP / 256;
    buffer[13] = ETH_P_ARP % 256;
    /*Fill in ARP header fileds */
    send_arhdr.ar_htype = htons(ARPHRD_LARP);
    send_arhdr.ar_ptype = htons(ETH_P_IP); /* code for IPV6 can be added as needed*/
    send_arhdr.ar_hln = ETH_ALEN;
    send_arhdr.ar_pln = IP_ADDR_SIZE;
    send_arhdr.ar_op = htons(LARP_REPLY_OP); /* LARP reply = 2 */
    /* source and destination MAC address */
    memcpy(&send_arhdr.ar_sha, s_haddr, ETH_ALEN * sizeof(uint8_t));
    memcpy(&send_arhdr.ar_tha, ar_hdr->ar_sha, ETH_ALEN * sizeof(uint8_t));
    /* Source and destination IP filled using received LARP request */
    memcpy(&send_arhdr.ar_sip, ar_hdr->ar_tip, IP_ADDR_SIZE * sizeof(uint8_t));
    memcpy(&send_arhdr.ar_tip, ar_hdr->ar_sip, IP_ADDR_SIZE * sizeof(uint8_t));

    /* Copying ARP header to sending packet buffer */
    memcpy(buffer + ETH_HDR_SIZE, &send_arhdr, sizeof(struct arphdr));

    /*Fill in type, length and label for TLV_LST */
    fill_type_label_stack(&type_len, l_stack, ar_hdr->ar_tip);

    /* copy the tlv TLV_LST struct to sending buffer */
    memcpy(buffer + ETH_HDR_SIZE + ARP_HDR_SIZE, &type_len, TYPE_LEN_SIZE);
    memcpy(buffer + ETH_HDR_SIZE + ARP_HDR_SIZE + TYPE_LEN_SIZE, l_stack, label_count * LABEL_STACK_SIZE);

    /*Add Attribute TLV to sending buffer only if it is enabled */
    if(attr_tlv_flag) {
        /* zero the type_len struct so that now the new values can be held for attr_tlv*/
        memset (&type_len, 0, TYPE_LEN_SIZE);

        /* Fill in struct values for attributes TLV */
        fill_type_attribute_tlv(&type_len, &a_tlv, ar_hdr->ar_tip);
        /* Copy the ATTR_TLV struct to the sending buffer */
        memcpy(buffer + ETH_HDR_SIZE + ARP_HDR_SIZE + TYPE_LEN_SIZE + label_count * LABEL_STACK_SIZE, &type_len, TYPE_LEN_SIZE);
        memcpy(buffer + ETH_HDR_SIZE + ARP_HDR_SIZE + TYPE_LEN_SIZE + label_count * LABEL_STACK_SIZE + TYPE_LEN_SIZE, &a_tlv, ATTR_TLV_SIZE);
    }

    /* Frame length = Ethernet header + ARP header + type_len + label_stack */
    frame_length = ETH_HDR_SIZE + ARP_HDR_SIZE + TYPE_LEN_SIZE + label_count * LABEL_STACK_SIZE + attr_tlv_flag * (TYPE_LEN_SIZE + ATTR_TLV_SIZE);

    /* sending the filled packet buffer using sendto*/
    send_bytes = sendto(send_sockfd, buffer, frame_length, 0, (SA *) &send_addr, sizeof(send_addr));
    if(send_bytes <= 0) { /* Return value: 0 is no bytes sent and negative is error */
        perror("Sendto() for LARP reply failed\n");
        exit (1);
    }
    get_interface_name (send_addr.sll_ifindex, if_name);
    printf("Sent LARP reply to %u.%u.%u.%u for target %u.%u.%u.%u on interface: %s with label(s): ", send_arhdr.ar_tip[0], send_arhdr.ar_tip[1], send_arhdr.ar_tip[2], send_arhdr.ar_tip[3], send_arhdr.ar_sip[0], send_arhdr.ar_sip[1], send_arhdr.ar_sip[2], send_arhdr.ar_sip[3],if_name);
    u32fromu8(send_arhdr.ar_sip, &ipaddr_n32);
    uint32_t *label_stk = (uint32_t *) calloc (0, label_count * sizeof(uint32_t));
    memcpy(label_stk, find_label(ipaddr_n32), label_count * sizeof(uint32_t));
    print_label_stack(label_stk);
    metric_val = find_metric(ipaddr_n32);
    if (metric_val != 0)
        printf("and with metric: %u\n", find_metric(ipaddr_n32));
    else
        printf("and with no ATTR_TLV.\n");
    if (hex_dump_flag) /* print hex_dump of packet if flag enabled */
        hexDump (ntohs(send_arhdr.ar_op), buffer+14 , frame_length - 14);
    /* freeing dynamically allocated memory */
    free (label_stk);
    free(s_haddr);
    free(l_stack);
}
Ejemplo n.º 26
0
extern int main(int argc, char *argv[])
{
	const char *filename_cstr = "test.aaf";

#ifndef _MSC_VER
	setlocale (LC_ALL, "en_US.UTF-8");
#endif

	if (argc >= 2)
	{
		filename_cstr = argv[1];
	}

	// convert C str to wide string
	aafWChar filename[FILENAME_MAX];
	size_t status = mbstowcs(filename, filename_cstr, sizeof(filename));
	if (status == (size_t)-1) {
		fprintf(stderr, "mbstowcs failed for \"%s\"\n", filename_cstr);
		return 1;
	}
	remove(filename_cstr);

	IAAFFile *pFile = NULL;
	int mode = 0;

	aafProductIdentification_t productID;
	aafProductVersion_t TestVersion = {1, 1, 0, 0, kAAFVersionUnknown};
	productID.companyName = (aafCharacter*)L"HSC";
	productID.productName = (aafCharacter*)L"String Tester";
	productID.productVersion = &TestVersion;
	productID.productVersionString = NULL;
	productID.productID = TestProductID;
	productID.platform = (aafCharacter*)L"Linux";

	// Create new AAF file
	check(AAFFileOpenNewModify(filename, mode, &productID, &pFile));

	// Create a simple Mob
	IAAFClassDef	*classDef = NULL;
	IAAFMob			*pMob = NULL;
	IAAFHeader		*pHeader = NULL;
	IAAFDictionary	*pDictionary = NULL;

	check(pFile->GetHeader(&pHeader));
	check(pHeader->GetDictionary(&pDictionary));
	check(pDictionary->LookupClassDef(AUID_AAFMasterMob, &classDef));
	check(classDef->CreateInstance(IID_IAAFMob, (IUnknown **)&pMob));
	classDef->Release();

	
	check(pMob->SetMobID(TEST_MobID));

	// UTF-8 for codepoint U+1D11E (musical G Clef): 0xf0,0x9d,0x84,0x9e
	// UTF-8 for codepoint U+1D122 (musical F Clef): 0xf0,0x9d,0x84,0xa2
	// http://unicode.org/charts/PDF/U1D100.pdf 
	// http://en.wikipedia.org/wiki/UTF-8
	aafCharacter *mobname;
	const unsigned char inputStr[] = {	0xf0,0x9d,0x84,0x9e,	// U+1D11E
										0xf0,0x9d,0x84,0xa2,	// U+1D122
										0x4d, 0x6f, 0x62,		// 'M' 'o' 'b'
										0x0 };

	// Convert UTF-8 inputStr to native wchar_t representation (UTF-32 Unix, UTF-16 Windows)
	int wlen = 0, n;
#ifndef _MSC_VER
	int ret;
	char *p = (char *)inputStr;
	while ((ret = mblen(p, 4)) > 0)
	{ ++wlen; p+=ret; }
	mobname = new aafCharacter[wlen+1];
	n = mbstowcs(mobname, (const char *)inputStr, wlen+1);

	if (n == -1)
	{
		fprintf (stderr, "mbstowcs returned -1. Invalid multibyte string\n");
		exit(1);
	}
#else
	// Under Windows we must use MultiByteToWideChar() to get correct UTF-8 conversion to UTF-16
	// since mbstowcs() is broken for UTF-8.
	wlen = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, (LPCSTR)inputStr, -1, NULL, 0);
	if (wlen == 0)
	{
		fprintf (stderr, "MultiByteToWideChar returned 0. Invalid multibyte string\n");
		exit(1);
	}
	mobname = new aafCharacter[wlen];
	n = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, (LPCSTR)inputStr, -1, mobname, wlen);
	if (n == 0)
	{
		fprintf (stderr, "MultiByteToWideChar returned 0. Invalid multibyte string\n");
		exit(1);
	}
#endif

	// SetName() calls OMSimpleProperty::set() which does a memcpy of the mobname string
	// to an OMByte* variable 'bits()' at OMProperty.cpp:399
	// Found by setting an rwatch on mobname address.
	check(pMob->SetName(mobname));
	aafUInt32 size_before = 0;
	check(pMob->GetNameBufLen(&size_before));
	check(pHeader->AddMob(pMob));
	pMob->Release();
	pHeader->Release();
	pDictionary->Release();

	// All the work of storing to disk happens during Save()
	// The bits() variable is next read in OMType::contract() at OMType.cpp:137
	// which is called by ImplAAFTypeDefCharacter::externalize() at ImplAAFTypeDefCharacter.cpp:307
	// which is called by ImplAAFTypeDefString::externalize() at ImplAAFTypeDefString.cpp:584
	// which is called by OMSSStoredObject::save() at OMSSStoredObject.cpp:382
	check(pFile->Save());
	check(pFile->Close());
	pFile->Release();

	// OMCharacterStringProperty<CharacterType>::stringLength() at OMVariableSizePropertyT.h:80
	// calculates string length of AAF string properties

	// Read AAF file back in
	check(AAFFileOpenExistingRead(filename, mode, &pFile));

	// Get the Mob
	check(pFile->GetHeader(&pHeader));
	check(pHeader->LookupMob(TEST_MobID, &pMob));
	aafUInt32 size_after = 0;
	check(pMob->GetNameBufLen(&size_after));
	aafCharacter *mobname_after = new aafCharacter[size_after];
	check(pMob->GetName(mobname_after, size_after));

	// Compare Mob name before storing to disk with Mob name read back from disk
	int test_result = 0;
	if (size_before != size_after) {
		printf("size_before=%d != size_after=%d\n", size_before, size_after);
		test_result = 1;
	}
	else {
		if (memcmp(mobname, mobname_after, size_before) != 0) {
			printf("wchar_t* mobname and wchar_t* mobname_after differ:\n");
			printf("  %s\n", hexDump(mobname, size_before));
			printf("  %s\n", hexDump(mobname_after, size_after));
			test_result = 1;
		}
	}

	// Check if the multibyte (UTF-8) versions of mobname and mobname_after match.
	char *outputStr;
#ifndef _MSC_VER
	wlen = wcslen(mobname_after)*sizeof(aafCharacter) + 1;
	outputStr = new char [wlen];
	n = wcstombs (outputStr, mobname_after, wlen);
	if (n == -1)
	{
		fprintf(stderr, "Could not convert mobname_after to multibyte str\n");
		exit(1);
	}
#else
	wlen = WideCharToMultiByte(CP_UTF8, 0, mobname_after, -1, NULL, 0, NULL, NULL);
	if (wlen == 0)
	{
		fprintf (stderr, "Failed to convert mobname_after to multibyte string\n");
		exit(1);
	}
	outputStr = new char[wlen];

	wlen = WideCharToMultiByte(CP_UTF8, 0, mobname_after, -1, outputStr, wlen, NULL, NULL);
#endif

	if (strlen((char *)inputStr) != strlen(outputStr))
	{
		fprintf(stderr, "UTF-8 version of string: input length(%d) != output length(%d)\n", (int)strlen((char *)inputStr), (int)strlen(outputStr));
		test_result = 1;
	}

	if (strcmp((char *)inputStr, outputStr) != 0)
	{
		fprintf(stderr, "UTF-8 version of string: input and output strings differ\n");
		printf("  %s\n", hexDump(inputStr, strlen((char *)inputStr)));
		printf("  %s\n", hexDump(outputStr, strlen(outputStr)));
		test_result = 1;
	}

	pMob->Release();
	pHeader->Release();
	check(pFile->Close());
	pFile->Release();

	delete [] mobname;
	delete [] mobname_after;
	return test_result;
}
Ejemplo n.º 27
0
int main(int argc , char* argv[]){
    
    if (argc < 5){
        printf("usage:\n");
        printf("    ./%s <tunsrc> <tunsrc ip>"
                "<tundst> <tundst ip>\n", argv[0]);
        exit(1);
    }
    char tun_name[IFNAMSIZ];
    char ERRBUF[LIBNET_ERRBUF_SIZE];
    int nread;
    /* Connect to the device */
    strcpy(tun_name, argv[1]);
    int tun_src_fd = tun_alloc(tun_name, IFF_TUN|IFF_NO_PI);

    strcpy(tun_name, argv[3]);
    int tun_dst_fd = tun_alloc(tun_name, IFF_TUN|IFF_NO_PI);
    
    char* src_tun_ip = argv[2];
    char* dst_tun_ip = argv[4];
    
    libnet_t* libnet = libnet_init(LIBNET_LINK_ADV,
                                    "wlan1",
                                   ERRBUF );

    printf("binded to src %s - %s\n", argv[1], src_tun_ip);
    printf("binded to dst %s - %s\n", argv[3], dst_tun_ip);

    if(tun_src_fd < 0 || tun_dst_fd < 0){
        perror("Allocating interface");
        exit(1);
    }
    char buffer[1500];

    int ethLayerSize = 0;
    //int ethLayerSize = ETHER_H_SIZE;
    int ipLayerSize = ethLayerSize + IP4_H_SIZE;

    int maxfd = MAX(tun_src_fd, tun_dst_fd);
    
    int rawfd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);
    int rawipfd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);
    if (rawfd < 0){
        perror("raw socket");
        exit(2);
    }
    int one = 1;
    const int* val = &one;
    if(setsockopt(rawfd, 
        IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0){
        perror("setsockopt()");
        exit(2);
    }
    while(1) {
#if 1
        fd_set fdset;

        FD_ZERO(&fdset);
        FD_SET(tun_src_fd, &fdset); 
        FD_SET(tun_dst_fd, &fdset);
        int ret = select(maxfd+1, &fdset, NULL, NULL, NULL);
        
        if (ret<0){
            perror("select");
            exit(2);
        }

        if (FD_ISSET(tun_src_fd, &fdset)){
            nread = sread(tun_src_fd,buffer,sizeof(buffer));
            printf("src tun read %d bytes from \n", nread);
            if (nread >= ipLayerSize){
                ip_h* ip = (ip_h*)(buffer+ethLayerSize);
                //if (ip->protocol != 1){
                //    printf("ignoring\n");
                //    goto next;
                //}
                //setDstHw(buffer, hwLoc);
                //setSrcHw(buffer, hwTap2);
                //setSrcIp(buffer+ethLayerSize, "192.168.1.3");
                setSrcIp(buffer+ethLayerSize, "192.168.1.3");
                setDstIp(buffer+ethLayerSize, "192.168.1.24");
                updateIPChecksum(buffer + ethLayerSize);
                sendEth(hwWlan, hwLaptop, (uint8_t*)buffer + ethLayerSize, nread, libnet);
                //swrite(tun_src_fd, buffer, nread);
                //sendToKernal(rawipfd, "192.168.1.24", buffer + ethLayerSize + ipLayerSize,
                //                                    nread - (ethLayerSize + ipLayerSize));
            }else{
                printf("unknown packet\n");
            }
        }
        if (FD_ISSET(tun_dst_fd, &fdset)){
            nread = sread(tun_dst_fd,buffer,sizeof(buffer));
            printf("DST tun read %d bytes\n", nread);
            if (nread >= ipLayerSize){
                //setDstHw(buffer, hwLoc);
                //setSrcHw(buffer, hwTap1);
                setSrcIp(buffer+ethLayerSize, "44.44.44.44");
                setDstIp(buffer+ethLayerSize, "192.168.1.24");
                updateIPChecksum(buffer + ethLayerSize);
                //swrite(tun_src_fd, buffer, nread);
                swrite(tun_dst_fd, buffer, nread);
            }else{
                printf("unknown packet\n");
            }
        }
        continue;
        // DONE;
#endif
        nread = sread(tun_src_fd,buffer,sizeof(buffer));
        hexDump(buffer, nread);

        printf("Read %d bytes from device %s\n", nread, tun_name);

        if (nread >= ethLayerSize){
            ether_h *eth = (ether_h*) (buffer);
            if (nread >= ipLayerSize){
                ip_h* ip = (ip_h*)(buffer+ethLayerSize);
                struct in_addr addr;
                addr.s_addr = ip->srcIp;
                printf("src ip: %s\n", inet_ntoa(addr));
                switch((ip->protocol)){
                    case 1:     // icmp
                        printf("icmp");
                    break;
                    case 6:     // tcp
                        printf("tcp");
                    break;
                    default:
                    printf("unknown (%x)", ip->protocol);

                    break;

                }
                setSrcIp(buffer+ethLayerSize, dst_tun_ip);
                setDstIp(buffer+ethLayerSize, "127.0.0.1");
                //sendToKernal(rawfd, buffer, nread);
                // swap ip's here
            } 
        }
        printf("\n");
    
    }
    return 0;
}
Ejemplo n.º 28
0
size_t parsePdfObj( size_t startPos, uint8_t *buf, size_t endPos, int dataType, struct pdfObject *curObjPtr ) {
  size_t curPos = startPos, bufOffset = 0, sPos;
  uint8_t tmpByte = 0, status = 0, *destBuf;
  int offset = 0, objNum = 0, objRev = 0, count = 0, getNum = 0, i;
  char tmpStr[1024];
  char tmpBuf[4096];
  struct pdfObject *tmpObjPtr;

  /*
   * parse this object
   */

  if ( config->verbose )
    printf( ">> %lu/%lu [%s]\n", startPos, endPos, typeStrings[dataType] );

  /*
   * loop until we are at the end
   */

  while ( curPos < endPos ) {
    if ( dataType EQ PDF_TYPE_NONE ) {
#ifdef DEBUG
      if ( config->debug >= 5 )
	hexDump( curPos, buf+curPos, 64 );
#endif
      if ( buf[curPos] EQ ' ' | buf[curPos] EQ '\r' | buf[curPos] EQ '\n' | buf[curPos] EQ '\t' ) {
	/* white space */
	curPos++;
      } else if ( buf[curPos] EQ '<' ) {
	if ( buf[curPos+1] EQ '<' ) { /* dictionary */
	  curPos+=2;
	  if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	    return FAILED;
	  }
	  curObjPtr->type = PDF_TYPE_DICTIONARY;
	  curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_DICTIONARY, curObjPtr );
	} else { /* hex string */
	  curPos++;
	  if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	    return FAILED;
	  }
	  curObjPtr->type = PDF_TYPE_HEXSTRING; 
	  curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_HEXSTRING, curObjPtr );
	}
      } else if ( buf[curPos] EQ '(' ) { /* string */
	curPos++;
	if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	  return FAILED;
	}
	curObjPtr->type = PDF_TYPE_STRING; 
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_STRING, curObjPtr );
      } else if ( buf[curPos] EQ '/' ) { /* label */
	curPos++;
	if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	  return FAILED;
	}
	curObjPtr->type = PDF_TYPE_NAME; 
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_NAME, curObjPtr );
      } else if ( buf[curPos] EQ '[' ) {
	/* array */
	curPos++;
	if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	  return FAILED;
	}
	curObjPtr->type = PDF_TYPE_ARRAY; 
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_ARRAY, curObjPtr );
      } else if ( sscanf( buf+curPos, "%d %d %n%s", &objNum, &objRev, &offset, tmpStr ) EQ 3 ) { /* named object */
	if ( strncmp( tmpStr, "obj", 3 ) EQ 0 ) {
	  printf( "Object: %d %d\n", objNum, objRev );
	  curPos += ( offset + 3 );
	  if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	    return FAILED;
	  }
	  curObjPtr->type = PDF_TYPE_OBJECT;
	  curObjPtr->num = objNum;
	  curObjPtr->gen = objRev;
	  curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_OBJECT, curObjPtr );
	} else if ( tmpStr[0] EQ 'R' ) {
	  printf( "ObjRef: %d %d\n", objNum, objRev );
	  curPos += ( offset + 1 );
	  if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	    return FAILED;
	  }
	  curObjPtr->type = PDF_TYPE_REFERENCE;
	  curObjPtr->num = objNum;
	  curObjPtr->gen = objRev;
	  curObjPtr = curObjPtr->parent;
	  /* once we have loaded all objects, we will link all references to their real objects */
	} else {
	  if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	    return FAILED;
	  }
	  curObjPtr->type = PDF_TYPE_INTNUM;
	  curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_INTNUM, curObjPtr );
	}
      } else if ( isdigit( buf[curPos] ) || ( buf[curPos] EQ '-' ) || ( buf[curPos] EQ '+' ) ) { /* number */
	if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	  return FAILED;
	}
	curObjPtr->type = PDF_TYPE_INTNUM;
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_INTNUM, curObjPtr );
      } else if ( ( buf[curPos] EQ 't' ) || ( buf[curPos] EQ 'f' ) ) { /* boolean number */
	if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	  return FAILED;
	}
	curObjPtr->type = PDF_TYPE_BOOL;
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_BOOL, curObjPtr );
      } else if ( buf[curPos] EQ '%' ) { /* comment */
	curPos++;
        /* check if this is EOF */
        if ( strncmp( buf+curPos, "%EOF\n", 5 ) EQ 0 ) {
            curPos += 5;
            printf( "EOF\n" );
            curObjPtr->type = PDF_TYPE_EOF;
            curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_EOF, curObjPtr );

        } else {
            if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
                return FAILED;
            }
            curObjPtr->type = PDF_TYPE_COMMENT;
            curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_COMMENT, curObjPtr );
        }
      } else if ( strncmp( buf+curPos, "stream", 6 ) EQ 0 ) { /* stream */
	curPos += 6;
	if ( buf[curPos] EQ '\r' )
	  curPos++;
	if ( buf[curPos] EQ '\n' )
	  curPos++;
	if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	  return FAILED;
	}
	curObjPtr->type = PDF_TYPE_STREAM;
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_STREAM, curObjPtr );
      } else if ( strncmp( buf+curPos, "obj", 3 ) EQ 0 ) {
	/* object */
	curPos += 3;
	if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	  return FAILED;
	}
	curObjPtr->type = PDF_TYPE_OBJECT;
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_OBJECT, curObjPtr );
      } else if ( strncmp( buf+curPos, "xref", 4 ) EQ 0 ) {
          
	/* start of footer */
	curPos += 4;
	if ( ( curObjPtr = insertPdfObject( curObjPtr ) ) EQ NULL ) {
	  return FAILED;
	}
	curObjPtr->type = PDF_TYPE_FOOTER;
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_FOOTER, curObjPtr );
        
      } else if ( strncmp( buf+curPos, "startxref", 9 ) EQ 0 ) {
        curPos += 9;  
        curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_NONE, curObjPtr );
      } else if ( strncmp( buf+curPos, "endobj", 6 ) EQ 0 ) {
	return( curPos );

      } else if ( buf[curPos] EQ ']' ) {
	return( curPos );

      } else if ( strncmp( buf+curPos, ">>", 2 ) EQ 0 ) {
	return( curPos );

      } else if ( buf[curPos] EQ '>' ) {
	return( curPos );

      } else {
          if ( isprint( buf[curPos] ) )
              printf( "%c", buf[curPos] );
          else
              printf( "." );
	curPos++;
      }
    } else if ( dataType EQ PDF_TYPE_EOF ) {
        /* all data after EOF is suspect */
	if ( config->write ) {
	  writeStream( curPos, buf+curPos, endPos - curPos );
	} else
	  hexDump( curPos, buf+curPos, endPos - curPos );
        curPos = endPos;
    } else if ( dataType EQ PDF_TYPE_REALNUM ) {
      /* 3.4 = realNum */
      sPos = curPos;
      if ( ( buf[curPos] EQ '-' ) || ( buf[curPos] EQ '+' ) ) {
	tmpStr[curPos-sPos] = buf[curPos];
	curPos++;
      }
      while( isdigit( buf[curPos] ) || buf[curPos] EQ '.' ) {
	tmpStr[curPos-sPos] = buf[curPos];
	curPos++;
      }
      tmpStr[curPos-sPos] = '\0';
      printf( "Real Number: %s\n", safePrint( tmpBuf, sizeof( tmpBuf ), tmpStr ) );
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_INTNUM ) {
      /* 343 = intNum */
      sPos = curPos;

      if ( ( buf[curPos] EQ '-' ) || ( buf[curPos] EQ '+' ) )
	curPos++;

      while( ( isdigit( buf[curPos] ) ) || ( buf[curPos] EQ '.' ) ) {
	if ( buf[curPos] EQ '.' ) {
	  curObjPtr->type = PDF_TYPE_REALNUM;
	  return parsePdfObj( sPos, buf, endPos, PDF_TYPE_REALNUM, curObjPtr );
	}
	curPos++;
      }
      printf( "Integer: %d\n", atoi( buf+sPos ) );
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_BOOL ) {
      /* true | false = bool */

      if ( strncmp( buf+curPos, "true", 4 ) EQ 0 ) {
	/* true */
	printf( "Boolean: true\n" );
	curPos += 4;
      } else if ( strncmp( buf+curPos, "false", 5 ) EQ 0 ) {
	/* false */
	printf( "Boolean: false\n" );
	curPos += 5;
      } else
	curPos++;
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_EOL ) {
      /* \n\r | \n | \n\r\n\r = EOL */
      while( ( buf[curPos] EQ '\n' ) || ( buf[curPos] EQ '\r' ) ) {
	curPos++;
      }
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_COMMENT ) {
      /* % ... EOL = comment */
      sPos = curPos;
      while( ( buf[curPos] != '\r' ) && ( buf[curPos] != '\n' ) ) {
	tmpStr[curPos-sPos] = buf[curPos];
	curPos++;
      }
      tmpStr[curPos-sPos] = '\0';
      printf( "Comment: %s\n", safePrint( tmpBuf, sizeof( tmpBuf ), tmpStr ) );
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_NAME ) {
      /* / ... = name */
      sPos = curPos;
      while( ( buf[curPos] != '\r' ) &&
	     ( buf[curPos] != '\n' ) &&
	     ( buf[curPos] != ' ' ) &&
	     ( buf[curPos] != '[' ) &&
	     ( buf[curPos] != '<' ) &&
	     ( buf[curPos] != '/' ) &&
	     ( buf[curPos] != '(' ) &&
	     ( buf[curPos] != '>' ) &&
	     ( buf[curPos] != ']' ) &&
	     ( buf[curPos] != ')' ) ) {
	/* process label */
	tmpStr[curPos-sPos] = buf[curPos];
	curPos++;
      }
      tmpStr[curPos-sPos] = '\0';
      printf( "Name: %s\n", safePrint( tmpBuf, sizeof( tmpBuf ), tmpStr ) );
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_STRING ) {
      /* ( ... ) = literalString */
      /* XXX add octal notation '\000' */
      /* XXX handle escaped characters */
      while( buf[curPos] EQ ' ' ) {
	curPos++;
      }
      sPos = curPos;
      if ( strncmp( buf+curPos, "254 255", 7 ) EQ 0 ) {
	curObjPtr->type = PDF_TYPE_UTFSTRING;
	return parsePdfObj( curPos, buf, endPos, PDF_TYPE_UTFSTRING, curObjPtr );
      } else if ( ( buf[curPos] EQ 'D' ) && ( buf[curPos+1] EQ ':' ) ) {
	curObjPtr->type = PDF_TYPE_DATESTRING;
	return parsePdfObj( curPos, buf, endPos, PDF_TYPE_DATESTRING, curObjPtr );
      }

      while( buf[curPos] != ')' ) {
	tmpStr[curPos-sPos] = buf[curPos];
	curPos++;
      }
      tmpStr[curPos-sPos] = '\0';
      printf( "String: %s\n", safePrint( tmpBuf, sizeof( tmpBuf ), tmpStr ) );
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos + 1 );

    } else if ( dataType EQ PDF_TYPE_UTFSTRING ) {
      /* ( 254 255 ... ) = utf encoded literal string */
      while( sscanf( buf+curPos, "%u%n", (unsigned int *)&tmpByte, &offset ) EQ 1 ) {
	curPos += offset;
	if ( buf[curPos] EQ ' ' ) {
	  curPos++;
	}
      }
      while( buf[curPos] != ')' ) {
	curPos++;
      }
      curPos++;
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_DATESTRING ) {
      sPos = curPos;
      /* (D:YYYYMMDDHHmmSSOHH'mm') = date encoded literal string */
      while( buf[curPos] != ')' ) {
	tmpStr[curPos-sPos] = buf[curPos];
	curPos++;
      }
      curPos++;
      tmpStr[curPos-sPos] = '\0';
      printf( "Date String: %s\n", safePrint( tmpBuf, sizeof( tmpBuf ), tmpStr ) );
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_HEXSTRING ) {
      /* < ... > = hexString */
      count = 0;
      sPos = curPos;
      while( buf[curPos] != '>' ) {
	if ( isxdigit( buf[curPos] ) )
	  tmpStr[count++] = buf[curPos];
	curPos++;
      }
      /* append a zero is the string length is odd */
      if ( !( count % 2 ) EQ 0 ) {
	tmpStr[count++] = '0';
      }
      tmpStr[count] = '\0';
      curPos++;
      printf( "HEX String: %s\n", safePrint( tmpBuf, sizeof( tmpBuf ), tmpStr ) );
      for( i = 0, offset = 0; i < count; i += 2 ) {
	tmpStr[offset++] = xtoi( tmpStr+i, 2 );
      }
      hexDump( 0, tmpStr, offset );
      printf( "HEX String: %s\n", safePrint( tmpBuf, sizeof( tmpBuf ), tmpStr ) );
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_UTFHEXSTRING ) {
      /* < fe ff ... > = utf encoded hex string */
      sPos = curPos;


    } else if ( dataType EQ PDF_TYPE_ARRAY ) {
      /* [ ... ] = array NOTE can be an array of any n objects */
      while( buf[curPos] != ']' ) {
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_NONE, curObjPtr );
      }
      curPos++;
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_DICTIONARY ) {
      /* << /Kids [ 1 0 R 1 0 R ]  = name tree */
      /*    /Names [ (key1) 1 0 R (key2) 2 0 R ] */
      /*    /Limits [ (firstKey) (lastKey) ] */
      /* << name ... >> = dictionary where key is a name and value can be any object */
      /* XXX organize into name, value pairs */
      while( strncmp( buf+curPos, ">>", 2 ) != 0 ) {
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_NONE, curObjPtr );
      }
      curPos += 2;
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );
      
    } else if ( dataType EQ PDF_TYPE_OBJECT ) {
      /* 3 0 obj ... endobj = turns any object into an indirect (referencable) object */
      /*                      3 = objNum, 0 = objRev */
      while ( strncmp( buf+curPos, "endobj", 6 ) != 0 ) {
	curPos = parsePdfObj( curPos, buf, endPos, PDF_TYPE_NONE, curObjPtr );
      }
      curPos += 6;
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[PDF_TYPE_OBJECT] );
      return( curPos );

    } else if ( dataType EQ PDF_TYPE_STREAM ) {
      /* XXX add code to associate the stream dictionary with the stream data */
      /* << ... >>EOLstream\n\r or \r ... \n\r endstream = stream */
      sPos = curPos;

      while( strncmp( buf+curPos, "endstream", 9 ) != 0 ) {
	curPos++;
      }

      printf( "Stream: %lu bytes\n", curPos - sPos );

      /* allocate buffer for decompressed stream */
      if ( ( destBuf = XMALLOC( ( curPos - sPos ) * 4 ) ) EQ NULL ) {
	fprintf( stderr, "ERR - Unable to allocate memory for stream\n" );
	exit( 1 );
      }
      XMEMSET( destBuf, 0, ( curPos-sPos ) * 4 );

      /* decompress the stream */
      z_stream zstrm;
      XMEMSET( &zstrm, 0, sizeof(zstrm) );
      zstrm.avail_in = curPos-sPos;
      zstrm.avail_out = ( curPos-sPos ) * 4;
      zstrm.next_in = buf+sPos;
      zstrm.next_out = destBuf;
      int rsti = inflateInit(&zstrm);
      if (rsti EQ Z_OK) {
	int rst2 = inflate (&zstrm, Z_FINISH);
	if (rst2 >= 0) {
	  if ( config->write ) {
	    writeStream( sPos, destBuf, zstrm.total_out );
	  } else
	    hexDump( 0, destBuf, zstrm.total_out );
	} else {
	  printf( "Stream did not decompress\n" );
	  if ( config->write ) {
	    writeStream( sPos, buf+sPos, curPos-sPos );
	  } else
	    hexDump( sPos, buf+sPos, curPos-sPos );
	}
      }

      XFREE( destBuf );

      curPos += 9;

      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      return( curPos );
      
    } else if ( dataType EQ PDF_TYPE_HEADER ) {
      /* %PDF-1.6EOL%nnnnEOL = file header where each n is > 128 to make file look binary */

    } else if ( dataType EQ PDF_TYPE_FOOTER ) {
      /* xref ... trailer ... startxref ... %%EOF = document footer */
      /* XXX making an asumption, big mistake */
      
      /* 0 271 */
      /* 0000000000 65535 f */
      /* 0000000015 00000 n */
      
      /* found the xref, now look for the trailer, startxref and finally the EOF */
      
      fprintf( stderr, "PDF Footer\n" );
      
      /* XXX need to parse xref table, may be multiple tables in the file */
      
      if ( strncmp( buf+curPos, "trailer", 7 ) EQ 0 ) {
          printf( "trailer\n" );
          curPos += 7;
      } else
          curPos++;
      
      if ( config->verbose )
	printf( "<< %lu/%lu [%s]\n", curPos, endPos, typeStrings[dataType] );
      
      return( curPos );
    }
  }

  return( curPos );
}
Ejemplo n.º 29
0
 // Output hexdump to a text stream
 void intoTextStream(QTextStream &strm) {
     outstrm = &strm;
     hexDump();
 }
Ejemplo n.º 30
0
void bufDump(const char *what, const buf_t buf) {
  char desc[1024];
  sprintf(desc, "%s (len=%lu, cap=%lu)", what, buf.len, buf.cap);
  hexDump(desc, buf.buf, buf.len);
}