void OpenSSLCertificate::parse() {
	if (!cert) {
		return;
	}

	// Subject name
	X509_NAME* subjectName = X509_get_subject_name(cert.get());
	if (subjectName) {
		// Subject name
		ByteArray subjectNameData;
		subjectNameData.resize(256);
		X509_NAME_oneline(X509_get_subject_name(cert.get()), reinterpret_cast<char*>(subjectNameData.getData()), subjectNameData.getSize());
		this->subjectName = std::string(reinterpret_cast<const char*>(subjectNameData.getData()));

		// Common name
		int cnLoc = X509_NAME_get_index_by_NID(subjectName, NID_commonName, -1);
		while (cnLoc != -1) {
			X509_NAME_ENTRY* cnEntry = X509_NAME_get_entry(subjectName, cnLoc);
			ASN1_STRING* cnData = X509_NAME_ENTRY_get_data(cnEntry);
			commonNames.push_back(ByteArray(cnData->data, cnData->length).toString());
			cnLoc = X509_NAME_get_index_by_NID(subjectName, NID_commonName, cnLoc);
		}
	}

	// subjectAltNames
	int subjectAltNameLoc = X509_get_ext_by_NID(cert.get(), NID_subject_alt_name, -1);
	if(subjectAltNameLoc != -1) {
		X509_EXTENSION* extension = X509_get_ext(cert.get(), subjectAltNameLoc);
		boost::shared_ptr<GENERAL_NAMES> generalNames(reinterpret_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(extension)), GENERAL_NAMES_free);
		boost::shared_ptr<ASN1_OBJECT> xmppAddrObject(OBJ_txt2obj(ID_ON_XMPPADDR_OID, 1), ASN1_OBJECT_free);
		boost::shared_ptr<ASN1_OBJECT> dnsSRVObject(OBJ_txt2obj(ID_ON_DNSSRV_OID, 1), ASN1_OBJECT_free);
		for (int i = 0; i < sk_GENERAL_NAME_num(generalNames.get()); ++i) {
			GENERAL_NAME* generalName = sk_GENERAL_NAME_value(generalNames.get(), i);
			if (generalName->type == GEN_OTHERNAME) {
				OTHERNAME* otherName = generalName->d.otherName;
				if (OBJ_cmp(otherName->type_id, xmppAddrObject.get()) == 0) {
					// XmppAddr
					if (otherName->value->type != V_ASN1_UTF8STRING) {
						continue;
					}
					ASN1_UTF8STRING* xmppAddrValue = otherName->value->value.utf8string;
					addXMPPAddress(ByteArray(ASN1_STRING_data(xmppAddrValue), ASN1_STRING_length(xmppAddrValue)).toString());
				}
				else if (OBJ_cmp(otherName->type_id, dnsSRVObject.get()) == 0) {
					// SRVName
					if (otherName->value->type != V_ASN1_IA5STRING) {
						continue;
					}
					ASN1_IA5STRING* srvNameValue = otherName->value->value.ia5string;
					addSRVName(ByteArray(ASN1_STRING_data(srvNameValue), ASN1_STRING_length(srvNameValue)).toString());
				}
			}
			else if (generalName->type == GEN_DNS) {
				// DNSName
				addDNSName(ByteArray(ASN1_STRING_data(generalName->d.dNSName), ASN1_STRING_length(generalName->d.dNSName)).toString());
			}
		}
	}
}
OpenSSLCertificate::OpenSSLCertificate(const ByteArray& der) {
#if OPENSSL_VERSION_NUMBER <= 0x009070cfL
	unsigned char* p = const_cast<unsigned char*>(der.getData());
#else
	const unsigned char* p = der.getData();
#endif
	cert = boost::shared_ptr<X509>(d2i_X509(NULL, &p, der.getSize()), X509_free);
	if (!cert) {
		SWIFT_LOG(warning) << "Error creating certificate from DER data" << std::endl;
	}
	parse();
}
void OpenSSLContext::sendPendingDataToApplication() {
	ByteArray data;
	data.resize(SSL_READ_BUFFERSIZE);
	int ret = SSL_read(handle_, data.getData(), data.getSize());
	while (ret > 0) {
		data.resize(ret);
		onDataForApplication(data);
		data.resize(SSL_READ_BUFFERSIZE);
		ret = SSL_read(handle_, data.getData(), data.getSize());
	}
	if (ret < 0 && SSL_get_error(handle_, ret) != SSL_ERROR_WANT_READ) {
		state_ = Error;
		onError();
	}
}
Example #4
0
//------------------------------------------------------------------------------
SerialPort::Error SerialPortWindows::driverGetRxBytes(ByteArray& byteArray,
													  const unsigned int nBytes)
{
	DWORD bytesReceived = 0;

	// TODO Fix this so it's non-blocking (overlapped I/O?)...

	if (!SetCommMask(mySerialHandle, EV_RXCHAR))
	{
	    // Error?
	}

//	DWORD dwCommEvent;
//
//	if (!WaitCommEvent(mySerialHandle, &dwCommEvent, NULL))
//	{
//	    return Error(ERROR_CODE_RX_FAILED);
//	}

	if (nBytes == 0)
	{
//	    byteArray.setSize(driverRxBytesAvailable());

		if (!ReadFile(mySerialHandle,
					  byteArray.getData(),
					  byteArray.getSize(),
					  &bytesReceived,
					  NULL))
		{
			return Error(ERROR_CODE_RX_FAILED);
		}
	}
	else
	{
		if (!ReadFile(mySerialHandle,
					  byteArray.getData(),
					  nBytes,
					  &bytesReceived,
					  NULL))
		{
			return Error(ERROR_CODE_RX_FAILED);
		}
	}

	byteArray.setSize(bytesReceived);

	return Error(ERROR_CODE_NONE);
}
ByteArray OpenSSLContext::getFinishMessage() const {
	ByteArray data;
	data.resize(MAX_FINISHED_SIZE);
	size_t size = SSL_get_finished(handle_, data.getData(), data.getSize());
	data.resize(size);
	return data;
}
void OpenSSLContext::sendPendingDataToNetwork() {
	int size = BIO_pending(writeBIO_);
	if (size > 0) {
		ByteArray data;
		data.resize(size);
		BIO_read(writeBIO_, data.getData(), size);
		onDataForNetwork(data);
	}
}
Example #7
0
String Settings::unEscape(const ByteArray &a) const {
  String result;

  size_t size = a.size();
  for(const BYTE *bp = a.getData(); size--; bp++) {
    result += unEscapeByte(*bp);
  }
  return result;
}
void OpenSSLContext::handleDataFromApplication(const ByteArray& data) {
	if (SSL_write(handle_, data.getData(), data.getSize()) >= 0) {
		sendPendingDataToNetwork();
	}
	else {
		state_ = Error;
		onError();
	}
}
Example #9
0
bool	Bullet::init(IGame* game, ByteArray const& params, float32 xStart) {
    if ((_game = game) == NULL) {
        return (false);
    }
    
    std::stringstream	data(std::stringstream::binary | std::stringstream::in | std::stringstream::out);
	data.write(params.getData(), params.getSize());
    
    Vec2 size;
    Vec3 from;
    Vec2 to;
    char *spriteName;
    uint32 spriteSize;
    char frameIndex;
    
    _xStart = xStart;
    
    data.read(reinterpret_cast<char*>(&spriteSize), sizeof(spriteSize));
    
    spriteName = new char[spriteSize];
	data.read(spriteName, spriteSize*sizeof(*spriteName));
	std::string name = std::string(spriteName, spriteSize);
	delete []spriteName;
    
    data.read(reinterpret_cast<char*>(&frameIndex), sizeof(frameIndex));
    
    data.read(reinterpret_cast<char*>(&size), sizeof(size));
    data.read(reinterpret_cast<char*>(&from), sizeof(from));
    data.read(reinterpret_cast<char*>(&_direction), sizeof(_direction));
    _direction.normalize();
    data.read(reinterpret_cast<char*>(&_speed), sizeof(_speed));
    
    ISprite	*sprite = _game->getLevelSprite(name);
	if (sprite == NULL)
		return false;
	if ((_graphicElement = game->createGraphicElement()) == NULL)
		return false;
	if ((_physicElement = game->createPhysicElement()) == NULL)
		return false;
    
    
	_graphicElement->setPosition(from);
	_graphicElement->setSize(size);
	_graphicElement->setRotation(0);
	_graphicElement->setSprite(sprite);
	_graphicElement->setSpriteFrameIndex(frameIndex);
	_graphicElement->setType(IGraphicElement::Static);
	game->addGraphicElement(_graphicElement);
	_physicElement->setPosition(from);
	_physicElement->setSize(size);
	_physicElement->setRotation(0);
	_physicElement->setType(IPhysicElement::Static);
	game->addPhysicElement(_physicElement);
    
    return true;
}
ByteArray OpenSSLCertificate::toDER() const {
	if (!cert) {
		return ByteArray();
	}

	ByteArray result;
	result.resize(i2d_X509(cert.get(), NULL));
	unsigned char* p = reinterpret_cast<unsigned char*>(result.getData());
	i2d_X509(cert.get(), &p);
	return result;
}
void OpenSSLContext::handleDataFromNetwork(const ByteArray& data) {
	BIO_write(readBIO_, data.getData(), data.getSize());
	switch (state_) {
		case Connecting:
			doConnect();
			break;
		case Connected:
			sendPendingDataToApplication();
			break;
		case Start: assert(false); break;
		case Error: /*assert(false);*/ break;
	}
}
Example #12
0
void Graphic::Image::loadFromData(ByteArray const& data) {
    sf::Image image;

    if (!image.loadFromMemory((void*)data.getData(), data.getSize())) {
        throw new Graphic::Exception("Cannot load image from data");
    }
    _width = image.getSize().x;
    _height = image.getSize().y;
    uint32 dataSize = _width * _height * 4;
    if (_pixels)
        delete[] _pixels;
    _pixels = new uint8[dataSize];
    memcpy((void*)_pixels, image.getPixelsPtr(), dataSize);
}
/**
 * Equality operator
 * 
 * @param byts const ByteArray&
 * @return bool
 */
bool ByteArray::operator== ( const ByteArray& byts) {

	//	Check if the arrays are the same length

	if ( getLength() != byts.getLength())
		return false;

	//	Check if the array is empty

	if (getLength() == 0)
		return true;

	//	Check if the array bytes are equal

	if ( memcmp( getData(), byts.getData(), getLength()) == 0)
		return true;
	return false;
}
Example #14
0
void SaveAsJob::doSave() {
  FILE *dst = MKFOPEN(m_newName, _T("wb"));
  try {
    ByteArray buffer;
    for(m_fileIndex = 0; (m_fileIndex < m_size) && !isInterrupted(); m_fileIndex += buffer.size()) {
      m_src.getBytes(m_fileIndex, 0x4000, buffer);
      if(buffer.size()) {
        FWRITE(buffer.getData(), 1, buffer.size(), dst);
      }
    }
    if(isInterrupted()) {
      throwException(_T("Save cancelled"));
    }
    fclose(dst);
    dst = NULL;
  } catch(...) {
    if(dst) {
      fclose(dst);
    }
    unlink(m_newName);
    m_ok = false;
    throw;
  }
}
HBITMAP decodeToBitmap(const ByteArray &bytes, PLPicDecoder &decoder, bool &hasAlpha) {
  HDC     dc     = NULL;
  HBITMAP bitmap = NULL;
  try {
    try {
      PLWinBmp winBmp;
      decoder.MakeBmpFromMemory((unsigned char*)bytes.getData(), (int)bytes.size(),&winBmp);
      const int width      = winBmp.GetWidth();
      const int height     = winBmp.GetHeight();
      const int totalBytes = winBmp.GetBytesPerLine() * height;

      dc     = getScreenDC();

#if WINVER >= 0x0500

      BITMAPV5HEADER bmHeader;
      ZeroMemory(&bmHeader, sizeof(bmHeader));
      bmHeader.bV5Size        = sizeof(bmHeader);
      bmHeader.bV5Width       = width;
      bmHeader.bV5Height      = height;
      bmHeader.bV5Planes      = 1;
      bmHeader.bV5BitCount    = winBmp.GetBitsPerPixel();
      bmHeader.bV5Compression = BI_BITFIELDS;
      bmHeader.bV5SizeImage   = totalBytes;
      bmHeader.bV5RedMask     = 0x000000ff;
      bmHeader.bV5GreenMask   = 0x0000ff00;
      bmHeader.bV5BlueMask    = 0x00ff0000;
      bmHeader.bV5AlphaMask   = 0xff000000;
      bmHeader.bV5CSType      = LCS_sRGB; // INDOWS_COLOR_SPACE;

#else

      BITMAPV4HEADER bmHeader;
      ZeroMemory(&bmHeader, sizeof(bmHeader));
      bmHeader.bV4Size          = sizeof(bmHeader);
      bmHeader.bV4Width         = width;
      bmHeader.bV4Height        = height;
      bmHeader.bV4Planes        = 1;
      bmHeader.bV4BitCount      = winBmp.GetBitsPerPixel();
      bmHeader.bV4V4Compression = BI_BITFIELDS;
      bmHeader.bV4SizeImage     = totalBytes;
      bmHeader.bV4RedMask       = 0x000000ff;
      bmHeader.bV4GreenMask     = 0x0000ff00;
      bmHeader.bV4BlueMask      = 0x00ff0000;
      bmHeader.bV4AlphaMask     = 0xff000000;
      bmHeader.bV4CSType        = LCS_sRGB; // INDOWS_COLOR_SPACE;

#endif

      BITMAPINFO bmInfo;
      ZeroMemory(&bmInfo, sizeof(bmInfo));
      bmInfo.bmiHeader.biSize        = sizeof(bmInfo);
      bmInfo.bmiHeader.biWidth       = width;
      bmInfo.bmiHeader.biHeight      = height; // positive gives bottom up bitmap
      bmInfo.bmiHeader.biPlanes      = 1;
      bmInfo.bmiHeader.biBitCount    = winBmp.GetBitsPerPixel();
      bmInfo.bmiHeader.biCompression = BI_RGB;
      bmInfo.bmiHeader.biSizeImage   = totalBytes;

      bitmap = CreateDIBitmap(dc,  (BITMAPINFOHEADER*)&bmHeader, CBM_INIT, winBmp.GetBits(), &bmInfo, DIB_RGB_COLORS);
      if(bitmap == NULL) {
        throwLastErrorOnSysCallException(_T("CreateDIBitmap"));
      }
      DeleteDC(dc);
      hasAlpha = winBmp.HasAlpha();

#ifdef TEST_DECODEBITMAP
      HDC screenDC = getScreenDC();
      if(hasAlpha) {
        showAlphaBitmap(screenDC, CPoint(100,100), bitmap);
      } else {
        showNormalBitmap(screenDC, CPoint(100,100), bitmap);
      }
      DeleteDC(screenDC);
#endif
      return bitmap;
    } catch(PLTextException e) {
      const String errMsg = e;
      throwException(errMsg);
      return NULL;
    }
  } catch(...) {
    if(bitmap) DeleteObject(bitmap);
    if(dc    ) DeleteDC(dc);
    throw;
  }
}
void CHexViewView::draw(CDC *dc) {
  CHexViewDoc *doc = GetDocument();
  ASSERT_VALID(doc);

  const CRect cr = updateSettings(dc);

  if(m_docSize > 0) {

    const bool    showAddr          = m_settings->getShowAddr();
    const bool    showAscii         = m_settings->getShowAscii();
    const __int64 indexByte0TopLine = m_topLine * m_lineSize;

    ByteArray content;
    doc->getBytes(indexByte0TopLine, m_lineSize * m_pageSize.cy, content);

    const BYTE      *buffer         = content.getData();
    const AddrRange  selection    = getSelection();

    if(showAddr) { // paint headline with offset from leftmost byte address
      dc->FillSolidRect(0, 0, cr.Width(), m_addrTextSize.cy, m_settings->getAddrBackColor());
      setAddrColor(dc, true);
      for(int col = 0, xPos = m_contentRect.left; col < m_lineSize; col++, xPos += m_byteSize.cx) {
        if(xPos > m_contentRect.right) {
          break;
        }
        dc->TextOut(xPos, 0, m_addrFormat.offsetToString(col).cstr());
      }
      setAddrColor(dc, false);
    }

#define OFFSET_LEFTMOSTBYTE(row) ((row)*m_lineSize + m_lineOffset)

    const BYTE *lastByte = &content[content.size()-1];
    setReverseVideo(dc, false);
    for(int row = 0, yPos = m_contentRect.top; yPos <= m_contentRect.bottom; row++, yPos += m_byteSize.cy) {
      const BYTE *bp = buffer + OFFSET_LEFTMOSTBYTE(row);
      if(bp > lastByte) {
        break;
      }
      if(showAddr) {
        setAddrColor(dc, true);
        dc->TextOut(0,yPos, getAddrAsString(indexByte0TopLine + OFFSET_LEFTMOSTBYTE(row)).cstr());
        setAddrColor(dc, false);
      }
      __int64 addr = indexByte0TopLine + OFFSET_LEFTMOSTBYTE(row);
      for(int col = 0, xPos = m_contentRect.left; (col < m_lineSize) && (xPos <= m_contentRect.right) && (bp <= lastByte); col++, xPos += m_byteSize.cx, bp++, addr++) {
        if(!selection.isEmpty()) {
          if(selection.contains(addr)) {
            if(!m_reverseVideo) {
              setReverseVideo(dc, true);
            }
          } else if(m_reverseVideo) {
            setReverseVideo(dc, false);
          }
        }

        TCHAR tmp[40];
        if(showAscii && isprint(*bp)) {
          if(!m_asciiColor) {
            setAsciiColor(dc, true);
          }
          _stprintf(tmp, m_asciiFormat, *bp);
        } else {
          if(m_asciiColor) {
            setAsciiColor(dc, false);
          }
          _stprintf(tmp, m_radixFormat, *bp);
        }
        dc->TextOut(xPos, yPos, tmp);
      }
    }
  }

  showCaret();

  if(m_maxTopLine == 0) { // all bytes shown. hide scrollbar
    ShowScrollBar(SB_VERT, FALSE);
  } else {
    // dont use SetScrollPos as it is only 16-bit int
    ShowScrollBar(SB_VERT, TRUE );

    updateVerticalScrollBar();
  }

  if(m_docSize == 0 || m_maxLineOffset == 0) {
    ShowScrollBar(SB_HORZ, FALSE);
  } else {
    ShowScrollBar(SB_HORZ, TRUE );
    SCROLLINFO scrollInfo;
    GetScrollInfo(SB_HORZ, &scrollInfo);
    scrollInfo.nMin  = 0;
    scrollInfo.nMax  = m_lineSize - 1;
    scrollInfo.nPos  = m_lineOffset;
    scrollInfo.nPage = m_pageSize.cx;
    SetScrollInfo(SB_HORZ, &scrollInfo);
  }
}
Example #17
0
ByteArray::ByteArray(const ByteArray &src) {
  init();
  if(!src.isEmpty()) {
    setData(src.getData(), src.size());
  }
}
/**
 * Copy constructor
 * 
 * @param byts const ByteArray&
 */
ByteArray::ByteArray( const ByteArray& byts) {
	m_data   = NULL;
	m_length = 0;

	setData( byts.getData(), byts.getLength());
}