<commit_before>//////////////////////////////////////////////////////////////////////////////////////
//
//
//	ScionCam -	mm_manager device adapter for scion 1394 cameras
//
//	Version	1.3
//
//	Copyright 2004-2009 Scion Corporation  		(Win XP/Vista, OS/X Platforms)
//
//	Implemented using Micro-Manager DemoCamera module as a baseline
//	Micro-Manager is copyright of University of California, San Francisco.
//
//////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// FILE:          capture.cpp
// PROJECT:       Micro-Manager
// SUBSYSTEM:     DeviceAdapters
//-----------------------------------------------------------------------------
// DESCRIPTION:   Scion Firewire Camera Device Adapter
//
// AUTHOR:        Scion Corporation, 2009
//
// COPYRIGHT:     Scion Corporation, 2004-2009
//
// LICENSE:       This file is distributed under the BSD license.
//                License text is included with the source distribution.
//
//                This file is distributed in the hope that it will be useful,
//                but WITHOUT ANY WARRANTY; without even the implied warranty
//                of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//                IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// CVS:           $Id: capture.cpp,v 1.33 2009/08/19 22:40:57 nenad Exp $
//

#ifdef WIN32
   #define WIN32_LEAN_AND_MEAN
   #include <windows.h>
   #define snprintf _snprintf
#endif

#include	"ScionCamera.h"
#include	<math.h>

extern	void	sLogMessage(char msg[]);

extern	int		command_period();

// local references

//----------------------------------------------------------------------------
//
//	get_frame() -	routine captures a frame
//
//					return -	0 = ok
//								1 = abort
//								2 = timeout
//								3 = stop continuous
//								4 = buffer overflow
//
//----------------------------------------------------------------------------

int CScionCamera::get_frame()
{
unsigned int	cc;
unsigned int	return_cc;

Cfw_image		*ip;

return_cc = 0;

restart_stream = 1;

// frame capture - using buffer 0

//cc = so.capture->start_frame();
//cc = so.capture->stop_frame();

cc = so.capture->get_frame();
if(cc == SFW_OK)
	{
	// frame complete

#ifdef	LOG_ENABLED
	sLogMessage("frame complete - get info\r\n");
#endif

	image_valid = 1;

	ip = so.capture->get_image();

	ii.buffer_no = so.capture->get_buffer_no();
	ii.bp = (unsigned char *)ip->get_bp();
	ii.format = ip->get_format();
	ii.depth = ip->get_component_depth();
	ii.image_mode = ip->get_image_type();
	ii.pi = ip;
	ii.image_valid = 1;
	}
else
	{
#ifdef	LOG_ENABLED
	sLogMessage("get image error\r\n");
#endif
	return_cc = 1;
	}

return(return_cc);
}

//----------------------------------------------------------------------------
//
//	start_snap() -	routine to start a snap
//
//					the frame capture is starting and this routine
//					blocks until exposure time has completed then returns.
//
//					does not wait for the readout and transfer
//
//----------------------------------------------------------------------------

int	CScionCamera::start_snap()
{
unsigned int	cc;
unsigned int	return_cc;

return_cc = 0;

restart_stream = 1;

// frame capture - using buffer 0

cc = so.capture->start_frame();

snap_in_progress = true;

// wait for exposure duration (exposure in ms)
CDeviceUtils::SleepMs((long)d_exposure);

return(return_cc);
}

//----------------------------------------------------------------------------
//
//	complete_snap() -	routine to check for frame complete
//
//						return -	0 = ok
//									1 = abort
//									2 = timeout
//									3 = stop continuous
//									4 = buffer overflow
//
//
//----------------------------------------------------------------------------

int	CScionCamera::complete_snap()
{
int			cc;
Cfw_image	*ip;

// wait for complete or time-out
cc = so.capture->stop_frame();

snap_in_progress = false;

if(cc != SFW_OK)
	{
	return(1);
	}

// frame complete

#ifdef	LOG_ENABLED
//sLogMessage("frame complete - get info\r\n");
#endif

image_valid = 1;

ip = so.capture->get_image();

ii.buffer_no = so.capture->get_buffer_no();
ii.bp = (unsigned char *)ip->get_bp();
ii.format = ip->get_format();
ii.depth = ip->get_component_depth();
ii.image_mode = ip->get_image_type();
ii.pi = ip;
ii.image_valid = 1;

return(0);
}

//----------------------------------------------------------------------------
//
//	start_frame() -	routine to initiate a frame capture sequence
//
//					this routine is used with double buffering
//
//
//----------------------------------------------------------------------------

int	CScionCamera::start_frame()
{
int					cc;

// start capture for selected buffer
cc = so.capture->start_frame();

return(1);
}

//----------------------------------------------------------------------------
//
//	complete_frame() -	routine to check for frame capture sequence complete
//
//						starts next frame.
//
//						this routine is used with double buffering
//
//						return -	0 = ok
//									1 = abort
//									2 = timeout
//									3 = stop continuous
//									4 = buffer overflow
//
//
//----------------------------------------------------------------------------

int	CScionCamera::complete_frame()
{
int			cc;
Cfw_image	*ip;

// wait for complete or time-out
cc = so.capture->complete_frame();
if(cc != SFW_OK)
	{
	return(1);
	}

// frame complete

image_valid = 1;

ip = so.capture->get_image();

ii.buffer_no = so.capture->get_buffer_no();
ii.bp = (unsigned char *)ip->get_bp();
ii.format = ip->get_format();
ii.depth = ip->get_component_depth();
ii.image_mode = ip->get_image_type();
ii.pi = ip;
ii.image_valid = 1;

return(0);
}

//----------------------------------------------------------------------------
//
//	available_frame() -	routine to get latest available frame
//
//						starts next frame.
//
//						this routine is used with double buffering
//
//						return -	0 = ok
//									1 = abort
//									2 = timeout
//									3 = stop continuous
//									4 = buffer overflow
//
//
//----------------------------------------------------------------------------

int	CScionCamera::available_frame()
{
int			cc;
Cfw_image	*ip;

// wait for complete or time-out
cc = so.capture->current_frame();
if(cc != SFW_OK)
	{
	return(1);
	}

// frame complete

image_valid = 1;

ip = so.capture->get_image();

ii.buffer_no = so.capture->get_buffer_no();
ii.bp = (unsigned char *)ip->get_bp();
ii.format = ip->get_format();
ii.depth = ip->get_component_depth();
ii.image_mode = ip->get_image_type();
ii.pi = ip;
ii.image_valid = 1;

return(0);
}

//----------------------------------------------------------------------------
//
//	IsCapturing() - returns true if sequence capture is active
//
//
//----------------------------------------------------------------------------

bool CScionCamera::IsCapturing()
{
return sequenceRunning_;
}

//----------------------------------------------------------------------------
//
//	InsertImage() - method to insert image into micro manager buffer pool
//
//----------------------------------------------------------------------------
int CScionCamera::InsertImage()
{
const unsigned char* img;

#ifdef	LOG_ENABLED
//sLogMessage("insert image in micro manager pool\r\n");
#endif

// call to GetImageBuffer will complete any pending capture
img = GetImageBuffer();
if (img == 0)
	{
	return DEVICE_ERR;
	}

int ret = GetCoreCallback()->InsertImage(this, img, GetImageWidth(),
								GetImageHeight(), GetImageBytesPerPixel());

if (!stopOnOverflow_ && ret == DEVICE_BUFFER_OVERFLOW)
	{
	// do not stop on overflow - just reset the buffer
	GetCoreCallback()->ClearImageBuffer(this);
	return(GetCoreCallback()->InsertImage(this, img,
				GetImageWidth(), GetImageHeight(), GetImageBytesPerPixel()));
	}
else
	{
	return ret;
	}
}

void CScionCamera::OnThreadExiting() throw()
{
   try
   {
      LogMessage(g_Msg_SEQUENCE_ACQUISITION_THREAD_EXITING);
      GetCoreCallback()->AcqFinished(this, 0);
   }
   catch (...)
   {
      LogMessage(g_Msg_EXCEPTION_IN_ON_THREAD_EXITING, false);
   }
}

//----------------------------------------------------------------------------
//
//	svc() - thread routine to perform sequence capture
//
//----------------------------------------------------------------------------

int CScionCamera::SequenceThread::svc()
{
long count(0);

// capture requested number of images
while (!stop_ && count < numImages_)
	{
	// get next image
	int ret = camera_->SnapImage();
	if (ret != DEVICE_OK)
		{
		camera_->StopSequenceAcquisition();
      camera_->OnThreadExiting();
		return(1);
		}

	// got image - insert image in micro manager buffer pool
	ret = camera_->InsertImage();
	if (ret != DEVICE_OK)
		{
		camera_->StopSequenceAcquisition();
      camera_->OnThreadExiting();
		return(1);
		}

	camera_->image_counter_++;
	count++;
	}

// sequence complete

camera_->OnThreadExiting();
camera_->sequenceRunning_ = false;

return(0);
}

#ifdef	ENABLE_SEQUENCE_ACQ
//----------------------------------------------------------------------------
//
//	StartSequenceAcquisition() - initiate sequence capture method
//
//
//----------------------------------------------------------------------------

int CScionCamera::StartSequenceAcquisition(long numImages,
				double interval_ms, bool stopOnOverflow)
{
#ifdef	LOG_ENABLED
sLogMessage("start seqquence acquisition\r\n");
#endif

if (Busy() || sequenceRunning_)
	{return DEVICE_CAMERA_BUSY_ACQUIRING;}

// prepare core
int ret = GetCoreCallback()->PrepareForAcq(this);
if (ret != DEVICE_OK)
	{return ret;}

// make sure the circular buffer is properly sized
GetCoreCallback()->InitializeImageBuffer(1, 1, GetImageWidth(),
							GetImageHeight(), GetImageBytesPerPixel());

stopOnOverflow_ = stopOnOverflow;
interval_ms = interval_ms;
sequenceLength_ = numImages;
image_counter_ = 0;

ctp->SetLength(numImages);
ctp->Start();

sequenceRunning_ = true;

return DEVICE_OK;
}

//----------------------------------------------------------------------------
//
//	RestartSequenceAcquisition() - method to restart sequence
//
//
//----------------------------------------------------------------------------

int CScionCamera::RestartSequenceAcquisition()
{
return StartSequenceAcquisition(sequenceLength_ - image_counter_,
										interval_ms_, stopOnOverflow_);
}

//----------------------------------------------------------------------------
//
//	StopSequenceAcquisition() - method to stop sequence capture
//
//
//----------------------------------------------------------------------------

int CScionCamera::StopSequenceAcquisition()
{
#ifdef	LOG_ENABLED
sLogMessage("stop sequence acquisition\r\n");
#endif

ctp->Stop();
ctp->wait();
sequenceRunning_ = false;
return DEVICE_OK;
}

#endif

<commit_msg>ScionCamera, figuring out why the shutter does not close when stopping live mode<commit_after>//////////////////////////////////////////////////////////////////////////////////////
//
//
//	ScionCam -	mm_manager device adapter for scion 1394 cameras
//
//	Version	1.3
//
//	Copyright 2004-2009 Scion Corporation  		(Win XP/Vista, OS/X Platforms)
//
//	Implemented using Micro-Manager DemoCamera module as a baseline
//	Micro-Manager is copyright of University of California, San Francisco.
//
//////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// FILE:          capture.cpp
// PROJECT:       Micro-Manager
// SUBSYSTEM:     DeviceAdapters
//-----------------------------------------------------------------------------
// DESCRIPTION:   Scion Firewire Camera Device Adapter
//
// AUTHOR:        Scion Corporation, 2009
//
// COPYRIGHT:     Scion Corporation, 2004-2009
//
// LICENSE:       This file is distributed under the BSD license.
//                License text is included with the source distribution.
//
//                This file is distributed in the hope that it will be useful,
//                but WITHOUT ANY WARRANTY; without even the implied warranty
//                of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//                IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// CVS:           $Id: capture.cpp,v 1.33 2009/08/19 22:40:57 nenad Exp $
//

#ifdef WIN32
   #define WIN32_LEAN_AND_MEAN
   #include <windows.h>
   #define snprintf _snprintf
#endif

#include	"ScionCamera.h"
#include	<math.h>

extern	void	sLogMessage(char msg[]);

extern	int		command_period();

// local references

//----------------------------------------------------------------------------
//
//	get_frame() -	routine captures a frame
//
//					return -	0 = ok
//								1 = abort
//								2 = timeout
//								3 = stop continuous
//								4 = buffer overflow
//
//----------------------------------------------------------------------------

int CScionCamera::get_frame()
{
unsigned int	cc;
unsigned int	return_cc;

Cfw_image		*ip;

return_cc = 0;

restart_stream = 1;

// frame capture - using buffer 0

//cc = so.capture->start_frame();
//cc = so.capture->stop_frame();

cc = so.capture->get_frame();
if(cc == SFW_OK)
	{
	// frame complete

#ifdef	LOG_ENABLED
	sLogMessage("frame complete - get info\r\n");
#endif

	image_valid = 1;

	ip = so.capture->get_image();

	ii.buffer_no = so.capture->get_buffer_no();
	ii.bp = (unsigned char *)ip->get_bp();
	ii.format = ip->get_format();
	ii.depth = ip->get_component_depth();
	ii.image_mode = ip->get_image_type();
	ii.pi = ip;
	ii.image_valid = 1;
	}
else
	{
#ifdef	LOG_ENABLED
	sLogMessage("get image error\r\n");
#endif
	return_cc = 1;
	}

return(return_cc);
}

//----------------------------------------------------------------------------
//
//	start_snap() -	routine to start a snap
//
//					the frame capture is starting and this routine
//					blocks until exposure time has completed then returns.
//
//					does not wait for the readout and transfer
//
//----------------------------------------------------------------------------

int	CScionCamera::start_snap()
{
unsigned int	cc;
unsigned int	return_cc;

return_cc = 0;

restart_stream = 1;

// frame capture - using buffer 0

cc = so.capture->start_frame();

snap_in_progress = true;

// wait for exposure duration (exposure in ms)
CDeviceUtils::SleepMs((long)d_exposure);

return(return_cc);
}

//----------------------------------------------------------------------------
//
//	complete_snap() -	routine to check for frame complete
//
//						return -	0 = ok
//									1 = abort
//									2 = timeout
//									3 = stop continuous
//									4 = buffer overflow
//
//
//----------------------------------------------------------------------------

int	CScionCamera::complete_snap()
{
int			cc;
Cfw_image	*ip;

// wait for complete or time-out
cc = so.capture->stop_frame();

snap_in_progress = false;

if(cc != SFW_OK)
	{
	return(1);
	}

// frame complete

#ifdef	LOG_ENABLED
//sLogMessage("frame complete - get info\r\n");
#endif

image_valid = 1;

ip = so.capture->get_image();

ii.buffer_no = so.capture->get_buffer_no();
ii.bp = (unsigned char *)ip->get_bp();
ii.format = ip->get_format();
ii.depth = ip->get_component_depth();
ii.image_mode = ip->get_image_type();
ii.pi = ip;
ii.image_valid = 1;

return(0);
}

//----------------------------------------------------------------------------
//
//	start_frame() -	routine to initiate a frame capture sequence
//
//					this routine is used with double buffering
//
//
//----------------------------------------------------------------------------

int	CScionCamera::start_frame()
{
int					cc;

// start capture for selected buffer
cc = so.capture->start_frame();

return(1);
}

//----------------------------------------------------------------------------
//
//	complete_frame() -	routine to check for frame capture sequence complete
//
//						starts next frame.
//
//						this routine is used with double buffering
//
//						return -	0 = ok
//									1 = abort
//									2 = timeout
//									3 = stop continuous
//									4 = buffer overflow
//
//
//----------------------------------------------------------------------------

int	CScionCamera::complete_frame()
{
int			cc;
Cfw_image	*ip;

// wait for complete or time-out
cc = so.capture->complete_frame();
if(cc != SFW_OK)
	{
	return(1);
	}

// frame complete

image_valid = 1;

ip = so.capture->get_image();

ii.buffer_no = so.capture->get_buffer_no();
ii.bp = (unsigned char *)ip->get_bp();
ii.format = ip->get_format();
ii.depth = ip->get_component_depth();
ii.image_mode = ip->get_image_type();
ii.pi = ip;
ii.image_valid = 1;

return(0);
}

//----------------------------------------------------------------------------
//
//	available_frame() -	routine to get latest available frame
//
//						starts next frame.
//
//						this routine is used with double buffering
//
//						return -	0 = ok
//									1 = abort
//									2 = timeout
//									3 = stop continuous
//									4 = buffer overflow
//
//
//----------------------------------------------------------------------------

int	CScionCamera::available_frame()
{
int			cc;
Cfw_image	*ip;

// wait for complete or time-out
cc = so.capture->current_frame();
if(cc != SFW_OK)
	{
	return(1);
	}

// frame complete

image_valid = 1;

ip = so.capture->get_image();

ii.buffer_no = so.capture->get_buffer_no();
ii.bp = (unsigned char *)ip->get_bp();
ii.format = ip->get_format();
ii.depth = ip->get_component_depth();
ii.image_mode = ip->get_image_type();
ii.pi = ip;
ii.image_valid = 1;

return(0);
}

//----------------------------------------------------------------------------
//
//	IsCapturing() - returns true if sequence capture is active
//
//
//----------------------------------------------------------------------------

bool CScionCamera::IsCapturing()
{
return sequenceRunning_;
}

//----------------------------------------------------------------------------
//
//	InsertImage() - method to insert image into micro manager buffer pool
//
//----------------------------------------------------------------------------
int CScionCamera::InsertImage()
{
const unsigned char* img;

#ifdef	LOG_ENABLED
//sLogMessage("insert image in micro manager pool\r\n");
#endif

// call to GetImageBuffer will complete any pending capture
img = GetImageBuffer();
if (img == 0)
	{
	return DEVICE_ERR;
	}

int ret = GetCoreCallback()->InsertImage(this, img, GetImageWidth(),
								GetImageHeight(), GetImageBytesPerPixel());

if (!stopOnOverflow_ && ret == DEVICE_BUFFER_OVERFLOW)
	{
	// do not stop on overflow - just reset the buffer
	GetCoreCallback()->ClearImageBuffer(this);
	return(GetCoreCallback()->InsertImage(this, img,
				GetImageWidth(), GetImageHeight(), GetImageBytesPerPixel()));
	}
else
	{
	return ret;
	}
}

void CScionCamera::OnThreadExiting() throw()
{
   try
   {
      LogMessage(g_Msg_SEQUENCE_ACQUISITION_THREAD_EXITING);
      GetCoreCallback()->AcqFinished(this, 0);
   }
   catch (...)
   {
      LogMessage(g_Msg_EXCEPTION_IN_ON_THREAD_EXITING, false);
   }
}

//----------------------------------------------------------------------------
//
//	svc() - thread routine to perform sequence capture
//
//----------------------------------------------------------------------------

int CScionCamera::SequenceThread::svc()
{
long count(0);

// capture requested number of images
while (!stop_ && count < numImages_)
{
	// get next image
	int ret = camera_->SnapImage();
	if (ret != DEVICE_OK)
   {
      camera_->sequenceRunning_ = false;
      camera_->OnThreadExiting();
		return(1);
   }

	// got image - insert image in micro manager buffer pool
	ret = camera_->InsertImage();
	if (ret != DEVICE_OK)
   {
      camera_->sequenceRunning_ = false;
      camera_->OnThreadExiting();
		return(1);
   }

	camera_->image_counter_++;
	count++;
}

// sequence complete
camera_->LogMessage("Exciting svc function");
camera_->OnThreadExiting();
camera_->sequenceRunning_ = false;

return(0);
}

#ifdef	ENABLE_SEQUENCE_ACQ
//----------------------------------------------------------------------------
//
//	StartSequenceAcquisition() - initiate sequence capture method
//
//
//----------------------------------------------------------------------------

int CScionCamera::StartSequenceAcquisition(long numImages,
				double interval_ms, bool stopOnOverflow)
{
#ifdef	LOG_ENABLED
sLogMessage("start seqquence acquisition\r\n");
#endif

if (Busy() || sequenceRunning_)
	{return DEVICE_CAMERA_BUSY_ACQUIRING;}

// prepare core
int ret = GetCoreCallback()->PrepareForAcq(this);
if (ret != DEVICE_OK)
	{return ret;}

// make sure the circular buffer is properly sized
GetCoreCallback()->InitializeImageBuffer(1, 1, GetImageWidth(),
							GetImageHeight(), GetImageBytesPerPixel());

stopOnOverflow_ = stopOnOverflow;
interval_ms = interval_ms;
sequenceLength_ = numImages;
image_counter_ = 0;

ctp->SetLength(numImages);
ctp->Start();

sequenceRunning_ = true;

return DEVICE_OK;
}

//----------------------------------------------------------------------------
//
//	RestartSequenceAcquisition() - method to restart sequence
//
//
//----------------------------------------------------------------------------

int CScionCamera::RestartSequenceAcquisition()
{
return StartSequenceAcquisition(sequenceLength_ - image_counter_,
										interval_ms_, stopOnOverflow_);
}

//----------------------------------------------------------------------------
//
//	StopSequenceAcquisition() - method to stop sequence capture
//
//
//----------------------------------------------------------------------------

int CScionCamera::StopSequenceAcquisition()
{
#ifdef	LOG_ENABLED
sLogMessage("stop sequence acquisition\r\n");
#endif

ctp->Stop();
ctp->wait();
sequenceRunning_ = false;
return DEVICE_OK;
}

#endif

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *       Michael Meeks <michael.meeks@suse.com>
 * Portions created by the Initial Developer are Copyright (C) 2011 the
 * Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Caolán McNamara <caolanm@redhat.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <sal/config.h>
#include <unotest/filters-test.hxx>
#include <test/bootstrapfixture.hxx>
#include <rtl/strbuf.hxx>
#include <osl/file.hxx>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/document/XFilter.hpp>

#include <sfx2/app.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include <svl/stritem.hxx>

#include <svx/svdtext.hxx>
#include <svx/svdotext.hxx>

#include "drawdoc.hxx"
#include "../source/ui/inc/DrawDocShell.hxx"

#include <osl/process.h>
#include <osl/thread.h>

/* Implementation of Filters test */

using namespace ::com::sun::star;

class SdFiltersTest
    : public test::FiltersTest
    , public test::BootstrapFixture
{
public:
    SdFiltersTest();

    ::sd::DrawDocShellRef loadURL( const rtl::OUString &rURL );
    virtual bool load(const rtl::OUString &, const rtl::OUString &, const rtl::OUString &) { return false; }
    virtual void setUp();
    virtual void tearDown();

    // FIXME: we should add some CVE tests ...
    void test();

    CPPUNIT_TEST_SUITE(SdFiltersTest);
    CPPUNIT_TEST(test);
    CPPUNIT_TEST_SUITE_END();

private:
    uno::Reference<document::XFilter> m_xFilter;
    uno::Reference<uno::XInterface> m_xDrawComponent;
};

#define PPTX_FORMAT_TYPE 268959811

struct FileFormat {
    const char* pName; const char* pFilterName; const char* pTypeName; sal_uLong nFormatType;
};

// cf. sc/qa/unit/filters-test.cxx and filters/...*.xcu to fill out.
FileFormat aFileFormats[] = {
    { "pptx" , "Impress MS PowerPoint 2007 XML", "MS PowerPoint 2007 XML", PPTX_FORMAT_TYPE },
    { 0, 0, 0, 0 }
};

::sd::DrawDocShellRef SdFiltersTest::loadURL( const rtl::OUString &rURL )
{
    FileFormat *pFmt;

    for (size_t i = 0; i < SAL_N_ELEMENTS (aFileFormats); i++)
    {
        pFmt = aFileFormats + i;
        if (pFmt->pName &&  rURL.endsWithIgnoreAsciiCaseAsciiL (pFmt->pName, strlen (pFmt->pName)))
            break;
    }
    CPPUNIT_ASSERT_MESSAGE( "missing filter info", pFmt->pName != NULL );

    sal_uInt32 nFormat = 0;
    if (pFmt->nFormatType)
        nFormat = SFX_FILTER_IMPORT | SFX_FILTER_USESOPTIONS;
    SfxFilter* aFilter = new SfxFilter(
        rtl::OUString::createFromAscii( pFmt->pFilterName ),
        rtl::OUString(), pFmt->nFormatType, nFormat,
        rtl::OUString::createFromAscii( pFmt->pTypeName ),
        0, rtl::OUString(), rtl::OUString(), /* userdata */
        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/sdraw*")) );
    aFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT);

    ::sd::DrawDocShellRef xDocShRef = new ::sd::DrawDocShell();
    SfxMedium* pSrcMed = new SfxMedium(rURL, STREAM_STD_READWRITE, true);
    pSrcMed->SetFilter(aFilter);
    CPPUNIT_ASSERT_MESSAGE( "load failed", xDocShRef->DoLoad(pSrcMed) );

    return xDocShRef;
}

void SdFiltersTest::test()
{
    ::sd::DrawDocShellRef xDocShRef = loadURL(getURLFromSrc("/sd/qa/unit/data/a.pptx"));
    CPPUNIT_ASSERT_MESSAGE( "failed to load", xDocShRef.Is() );
    CPPUNIT_ASSERT_MESSAGE( "not in destruction", !xDocShRef->IsInDestruction() );

    SdDrawDocument *pDoc = xDocShRef->GetDoc();
    CPPUNIT_ASSERT_MESSAGE( "no document", pDoc != NULL );

    // cf. SdrModel svx/svdmodel.hxx ...

    CPPUNIT_ASSERT_MESSAGE( "wrong page count", pDoc->GetPageCount() == 3);

    const SdrPage *pPage = pDoc->GetPage (1);
    CPPUNIT_ASSERT_MESSAGE( "no page", pPage != NULL );

    sal_uIntPtr nObjs = pPage->GetObjCount();
    for (sal_uIntPtr i = 0; i < nObjs; i++)
    {
        SdrObject *pObj = pPage->GetObj(i);
        SdrObjKind eKind = (SdrObjKind) pObj->GetObjIdentifier();
        SdrTextObj *pTxt = dynamic_cast<SdrTextObj *>( pObj );
        (void)pTxt; (void)eKind;
    }

    CPPUNIT_ASSERT_MESSAGE( "changed", !pDoc->IsChanged() );
    xDocShRef->DoClose();
}

SdFiltersTest::SdFiltersTest()
{
}

void SdFiltersTest::setUp()
{
    test::BootstrapFixture::setUp();

    // This is a bit of a fudge, we do this to ensure that ScGlobals::ensure,
    // which is a private symbol to us, gets called
    m_xDrawComponent =
        getMultiServiceFactory()->createInstance(rtl::OUString(
        RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.Draw.PresentationDocument")));
    CPPUNIT_ASSERT_MESSAGE("no impress component!", m_xDrawComponent.is());
}

void SdFiltersTest::tearDown()
{
    uno::Reference< lang::XComponent >( m_xDrawComponent, uno::UNO_QUERY_THROW )->dispose();
    test::BootstrapFixture::tearDown();
}

CPPUNIT_TEST_SUITE_REGISTRATION(SdFiltersTest);

CPPUNIT_PLUGIN_IMPLEMENT();

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>close file before the first assertion message if loading failed<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *       Michael Meeks <michael.meeks@suse.com>
 * Portions created by the Initial Developer are Copyright (C) 2011 the
 * Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Caolán McNamara <caolanm@redhat.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#include <sal/config.h>
#include <unotest/filters-test.hxx>
#include <test/bootstrapfixture.hxx>
#include <rtl/strbuf.hxx>
#include <osl/file.hxx>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/document/XFilter.hpp>

#include <sfx2/app.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include <svl/stritem.hxx>

#include <svx/svdtext.hxx>
#include <svx/svdotext.hxx>

#include "drawdoc.hxx"
#include "../source/ui/inc/DrawDocShell.hxx"

#include <osl/process.h>
#include <osl/thread.h>

/* Implementation of Filters test */

using namespace ::com::sun::star;

class SdFiltersTest
    : public test::FiltersTest
    , public test::BootstrapFixture
{
public:
    SdFiltersTest();

    ::sd::DrawDocShellRef loadURL( const rtl::OUString &rURL );
    virtual bool load(const rtl::OUString &, const rtl::OUString &, const rtl::OUString &) { return false; }
    virtual void setUp();
    virtual void tearDown();

    // FIXME: we should add some CVE tests ...
    void test();

    CPPUNIT_TEST_SUITE(SdFiltersTest);
    CPPUNIT_TEST(test);
    CPPUNIT_TEST_SUITE_END();

private:
    uno::Reference<document::XFilter> m_xFilter;
    uno::Reference<uno::XInterface> m_xDrawComponent;
};

#define PPTX_FORMAT_TYPE 268959811

struct FileFormat {
    const char* pName; const char* pFilterName; const char* pTypeName; sal_uLong nFormatType;
};

// cf. sc/qa/unit/filters-test.cxx and filters/...*.xcu to fill out.
FileFormat aFileFormats[] = {
    { "pptx" , "Impress MS PowerPoint 2007 XML", "MS PowerPoint 2007 XML", PPTX_FORMAT_TYPE },
    { 0, 0, 0, 0 }
};

::sd::DrawDocShellRef SdFiltersTest::loadURL( const rtl::OUString &rURL )
{
    FileFormat *pFmt;

    for (size_t i = 0; i < SAL_N_ELEMENTS (aFileFormats); i++)
    {
        pFmt = aFileFormats + i;
        if (pFmt->pName &&  rURL.endsWithIgnoreAsciiCaseAsciiL (pFmt->pName, strlen (pFmt->pName)))
            break;
    }
    CPPUNIT_ASSERT_MESSAGE( "missing filter info", pFmt->pName != NULL );

    sal_uInt32 nFormat = 0;
    if (pFmt->nFormatType)
        nFormat = SFX_FILTER_IMPORT | SFX_FILTER_USESOPTIONS;
    SfxFilter* aFilter = new SfxFilter(
        rtl::OUString::createFromAscii( pFmt->pFilterName ),
        rtl::OUString(), pFmt->nFormatType, nFormat,
        rtl::OUString::createFromAscii( pFmt->pTypeName ),
        0, rtl::OUString(), rtl::OUString(), /* userdata */
        rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("private:factory/sdraw*")) );
    aFilter->SetVersion(SOFFICE_FILEFORMAT_CURRENT);

    ::sd::DrawDocShellRef xDocShRef = new ::sd::DrawDocShell();
    SfxMedium* pSrcMed = new SfxMedium(rURL, STREAM_STD_READWRITE, true);
    pSrcMed->SetFilter(aFilter);
    if ( !xDocShRef->DoLoad(pSrcMed) )
    {
        if (xDocShRef.Is())
            xDocShRef->DoClose();
        CPPUNIT_ASSERT_MESSAGE( "failed to load", false );
    }

    return xDocShRef;
}

void SdFiltersTest::test()
{
    ::sd::DrawDocShellRef xDocShRef = loadURL(getURLFromSrc("/sd/qa/unit/data/a.pptx"));
    CPPUNIT_ASSERT_MESSAGE( "failed to load", xDocShRef.Is() );
    CPPUNIT_ASSERT_MESSAGE( "not in destruction", !xDocShRef->IsInDestruction() );

    SdDrawDocument *pDoc = xDocShRef->GetDoc();
    CPPUNIT_ASSERT_MESSAGE( "no document", pDoc != NULL );

    // cf. SdrModel svx/svdmodel.hxx ...

    CPPUNIT_ASSERT_MESSAGE( "wrong page count", pDoc->GetPageCount() == 3);

    const SdrPage *pPage = pDoc->GetPage (1);
    CPPUNIT_ASSERT_MESSAGE( "no page", pPage != NULL );

    sal_uIntPtr nObjs = pPage->GetObjCount();
    for (sal_uIntPtr i = 0; i < nObjs; i++)
    {
        SdrObject *pObj = pPage->GetObj(i);
        SdrObjKind eKind = (SdrObjKind) pObj->GetObjIdentifier();
        SdrTextObj *pTxt = dynamic_cast<SdrTextObj *>( pObj );
        (void)pTxt; (void)eKind;
    }

    CPPUNIT_ASSERT_MESSAGE( "changed", !pDoc->IsChanged() );
    xDocShRef->DoClose();
}

SdFiltersTest::SdFiltersTest()
{
}

void SdFiltersTest::setUp()
{
    test::BootstrapFixture::setUp();

    // This is a bit of a fudge, we do this to ensure that ScGlobals::ensure,
    // which is a private symbol to us, gets called
    m_xDrawComponent =
        getMultiServiceFactory()->createInstance(rtl::OUString(
        RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.Draw.PresentationDocument")));
    CPPUNIT_ASSERT_MESSAGE("no impress component!", m_xDrawComponent.is());
}

void SdFiltersTest::tearDown()
{
    uno::Reference< lang::XComponent >( m_xDrawComponent, uno::UNO_QUERY_THROW )->dispose();
    test::BootstrapFixture::tearDown();
}

CPPUNIT_TEST_SUITE_REGISTRATION(SdFiltersTest);

CPPUNIT_PLUGIN_IMPLEMENT();

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fudraw.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:32:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_FU_DRAW_HXX
#define SD_FU_DRAW_HXX

#ifndef _SV_POINTR_HXX //autogen
#include <vcl/pointr.hxx>
#endif

#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

struct SdrViewEvent;
class SdrObject;

namespace sd {

/*************************************************************************
|*
|* Basisklasse fuer alle Drawmodul-spezifischen Funktionen
|*
\************************************************************************/

class FuDraw
    : public FuPoor
{
public:
    TYPEINFO();

    FuDraw (ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);
    virtual ~FuDraw();

    virtual BOOL KeyInput(const KeyEvent& rKEvt);
    virtual BOOL MouseMove(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);
    virtual BOOL RequestHelp(const HelpEvent& rHEvt);

    virtual void ScrollStart();
    virtual void ScrollEnd();

    virtual void Activate();
    virtual void Deactivate();

    virtual void ForcePointer(const MouseEvent* pMEvt = NULL);

    virtual void DoubleClick(const MouseEvent& rMEvt);

    BOOL    SetPointer(SdrObject* pObj, const Point& rPos);
    BOOL    SetHelpText(SdrObject* pObj, const Point& rPos, const SdrViewEvent& rVEvt);

    void    SetPermanent(BOOL bSet) { bPermanent = bSet; }

    /** is called when the currenct function should be aborted.

        This is used when a function gets a KEY_ESCAPE but can also
        be called directly.

        @returns true if a active function was aborted
    */
    virtual bool cancel();

protected:
    Pointer aNewPointer;
    Pointer aOldPointer;
    BOOL    bMBDown;
    BOOL    bDragHelpLine;
    USHORT  nHelpLine;
    BOOL    bPermanent;
};

} // end of namespace sd

#endif      // _SD_FUDRAW_HXX
<commit_msg>INTEGRATION: CWS impressfunctions (1.5.40); FILE MERGED 2005/10/28 10:56:44 cl 1.5.40.1: #125341# reworked FuPoor classes to use refcounting<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fudraw.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-12-14 17:10:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_FU_DRAW_HXX
#define SD_FU_DRAW_HXX

#ifndef _SV_POINTR_HXX //autogen
#include <vcl/pointr.hxx>
#endif

#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

struct SdrViewEvent;
class SdrObject;

namespace sd {

/*************************************************************************
|*
|* Basisklasse fuer alle Drawmodul-spezifischen Funktionen
|*
\************************************************************************/

class FuDraw
    : public FuPoor
{
public:
    TYPEINFO();

    static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq, bool bPermanent );

    virtual BOOL KeyInput(const KeyEvent& rKEvt);
    virtual BOOL MouseMove(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);
    virtual BOOL RequestHelp(const HelpEvent& rHEvt);

    virtual void ScrollStart();
    virtual void ScrollEnd();

    virtual void Activate();
    virtual void Deactivate();

    virtual void ForcePointer(const MouseEvent* pMEvt = NULL);

    virtual void DoubleClick(const MouseEvent& rMEvt);

    BOOL    SetPointer(SdrObject* pObj, const Point& rPos);
    BOOL    SetHelpText(SdrObject* pObj, const Point& rPos, const SdrViewEvent& rVEvt);

    void    SetPermanent(BOOL bSet) { bPermanent = bSet; }

    /** is called when the currenct function should be aborted.

        This is used when a function gets a KEY_ESCAPE but can also
        be called directly.

        @returns true if a active function was aborted
    */
    virtual bool cancel();

protected:
    FuDraw (ViewShell* pViewSh,
        ::sd::Window* pWin,
        ::sd::View* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);

    virtual ~FuDraw();

    Pointer aNewPointer;
    Pointer aOldPointer;
    BOOL    bMBDown;
    BOOL    bDragHelpLine;
    USHORT  nHelpLine;
    BOOL    bPermanent;

};

} // end of namespace sd

#endif      // _SD_FUDRAW_HXX
<|endoftext|>


<commit_before>#include "crypto.h"
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include "sha256.h"

const int PACKET_DATA_LENGTH = 32;    //bytes
const int PACKET_CHECKSUM_LENGTH = 32;
const int PACKET_LENGTH = PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH;

char* OTP(unsigned long long* index, const unsigned long long amount);
char* xorCharArray(const char* first, const char* second, unsigned long long length);
unsigned long long unsignedLongLongRand();
char* longToCharArray(unsigned long long num, int size);
unsigned long long charArrayToLong(const char* data, int size);
bool charArrayEquals(const char* data1, const char* data2, int size);
char* concat(const char* left, const char* right, int sizel, int sizer);
char* sha_256(char* buf);

// send command
ssize_t cwrite(int fd, const void *buf, size_t len) {
	//long indexOfPad = random integer from 0 to size of OTP in bytes
	unsigned long long* indexOfPad = new unsigned long long;
	*indexOfPad = unsignedLongLongRand();
	//char* nonce = longToCharArray(&indexOfPad, PACKET_LENGTH);
	char* nonce = longToCharArray(*indexOfPad, PACKET_LENGTH);
	//send nonce to reciever
	int n;
	n = write(fd, nonce, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//1
	//char* myChecksum = xor(OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH), OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH));
	char* myChecksum = xorCharArray(OTP(indexOfPad,PACKET_LENGTH), OTP(indexOfPad, PACKET_LENGTH), PACKET_LENGTH);
	//2
	//byte* response = response from receiver
	char buffer[PACKET_LENGTH];
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if (n == 0) {
		//error - no message
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if(!charArrayEquals(buffer, myChecksum, PACKET_LENGTH)) {
		//myChecksum != response
		return -1;
	}
	//send ok to reciever
	n = write(fd, "OK", PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2.1
	//2.2
	//for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
	for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
		//char* toSend = buf[bufferIndex];
		char* toSend = buf[bufferIndex];
		//char* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(indexOfPad, PACKET_LENGTH);
		//char* mac = sha-256(concat(toSend, key));
		char* mac = sha_256(concat(toSend, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		//char* message = concat(toSend, mac);
		char* message = concat(toSend, mac, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH);
		//char* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(indexOfPad, PACKET_LENGTH);
		//send xor(message, pad) to reciever
		n = write(fd, xorCharArray(message, pad), PACKET_LENGTH);
		if (n < 0) {
			delete[] key;
			return -1;
		}
		delete[] key;
		//3
	}
}

// recv command
ssize_t cread(int fd, void *buf, size_t len) {
	//1
	//wait for nonce from sender
	char buffer[PACKET_LENGTH];
	int n;
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	//long indexOfPad;
	//indexOfPad = charArrayToLong(message recieved from sender);
	unsigned long long indexOfPad = charArrayToLong(buffer, PACKET_LENGTH);
	//byte* message = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* message = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* pad = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* reply = xor(message, pad);
	char* reply = xorCharArray(message, pad, PACKET_LENGTH);
	//send reply to sender
	n = write(fd, reply, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2
	//2.1
	//recieve ok, if not retry, abort, ignore?
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	else if(std::strcmp(buffer, "OK") != 0) {
		//error - not ok
		return -1;
	}
	//2.2
	//int amount_recv = 0;
	int amount_recv = 0;
	//while(more to recieve or amount_recv + PACKET_DATA_LENGTH < len) {
	while(amount_recv + PACKET_DATA_LENGTH < len) {
		//3
		//byte data[PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH] = message recieved from sender
		char data[PACKET_LENGTH];
		amount_recv += read(fd, data, PACKET_LENGTH);
		//byte* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(&indexOfPad, PACKET_LENGTH);
		//pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(&indexOfPad, PACKET_LENGTH);
		//byte* messsage = xor(data, pad);
		char* message = xorCharArray(data, pad, PACKET_LENGTH);
		//byte* checksum = data + PACKET_DATA_LENGTH;     checksum is last part after the data
		char* checksum = message + PACKET_DATA_LENGTH;
		//byte* mac = sha-256(concat(messsage, key));     recompute mac
		//std::string msgStr(message);
		//std::string keyStr(key);
		char* mac = sha_256(concat(message, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		if(!charArrayEquals(checksum, mac, PACKET_LENGTH)) {
			//checksum != mac
			delete[] mac;
			return -1;
		}

		//copy message into buffer
		for(int i = 0; i < PACKET_DATA_LENGTH; i++) {
			buf[i] = message[i];
		}
		buf += PACKET_DATA_LENGTH;
		delete[] mac;
	}
	return amount_recv;
}

char* OTP(unsigned long long* index, const unsigned long long amount) {
	std::ifstream pad;
	pad.open("otp.key");
	pad.seekg(*index);
	char* result = new char[amount];
	pad.read(result, amount);
	pad.close();
	*index += amount;
	return result;
	//byte pad[amount];  allocate amount bytes to return
	//seek to index in OTP
	//for(long i = 0; i < amount; i++)
		//pad[i] = readByte();  read in each byte from the file
	//*index += amount;  increment index so we don't use the same pad twice
	//return pad;
}

char* xorCharArray(const char* first, const char* second, unsigned long long length) {
	//byte result[length];
	char* result = new char[length];
	//for(long i = 0; i < length; i++) {
	for(unsigned long long i = 0; i < length; i++) {
		result[i] = first[i] ^ second[i];
	}
	return result;
}

unsigned long long unsignedLongLongRand() {
    unsigned long long rand1 = abs(rand());
    unsigned long long rand2 = abs(rand());
    rand1 <<= (sizeof(int)*8);
    unsigned long long randULL = (rand1 | rand2);
    return randULL;
}

char* longToCharArray(unsigned long long num, int size) {
	return reinterpret_cast<char*>(num);
}

unsigned long long charArrayToLong(const char* data, int size){
	return reinterpret_cast<unsigned long long>(data);
}

bool charArrayEquals(const char* data1, const char* data2, int size) {
	for(int i = 0; i < size; i++) {
		if(data1[i] != data2[i]) return false;
	}
	return true;
}

char* concat(const char* left, const char* right, int sizel, int sizer) {
	char* result = new char[sizel + sizer];
	for(int i = 0; i < sizel; i++) {
		result[i] = left[i];
	}
	for(int i = 0; i < sizer; i++) {
		result[sizel + i] = right[i];
	}
	return result;
	//std::string msgStr(left);
	//std::string keyStr(right);
	//return &(left + right)[0];
}

char* sha_256(char* buf) {
	return &sha256(buf)[0];
}
<commit_msg>fixed things<commit_after>#include "crypto.h"
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include "sha256.h"

const int PACKET_DATA_LENGTH = 32;    //bytes
const int PACKET_CHECKSUM_LENGTH = 32;
const int PACKET_LENGTH = PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH;

char* OTP(unsigned long long* index, const unsigned long long amount);
char* xorCharArray(const char* first, const char* second, unsigned long long length);
unsigned long long unsignedLongLongRand();
char* longToCharArray(unsigned long long num, int size);
unsigned long long charArrayToLong(const char* data, int size);
bool charArrayEquals(const char* data1, const char* data2, int size);
char* concat(const char* left, const char* right, int sizel, int sizer);
char* sha_256(char* buf);

// send command
ssize_t cwrite(int fd, const void *buf, size_t len) {
	//long indexOfPad = random integer from 0 to size of OTP in bytes
	unsigned long long* indexOfPad = new unsigned long long;
	*indexOfPad = unsignedLongLongRand();
	//char* nonce = longToCharArray(&indexOfPad, PACKET_LENGTH);
	char* nonce = longToCharArray(*indexOfPad, PACKET_LENGTH);
	//send nonce to reciever
	int n;
	n = write(fd, nonce, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//1
	//char* myChecksum = xor(OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH), OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH));
	char* myChecksum = xorCharArray(OTP(indexOfPad,PACKET_LENGTH), OTP(indexOfPad, PACKET_LENGTH), PACKET_LENGTH);
	//2
	//byte* response = response from receiver
	char buffer[PACKET_LENGTH];
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if (n == 0) {
		//error - no message
		n = write(fd, "NO", PACKET_LENGTH);
		if (n < 0) {
			return -1;
		}
		return -1;
	}
	else if(!charArrayEquals(buffer, myChecksum, PACKET_LENGTH)) {
		//myChecksum != response
		return -1;
	}
	//send ok to reciever
	n = write(fd, "OK", PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2.1
	//2.2
	//for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
	for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) {
		//char* toSend = buf[bufferIndex];
		char* toSend = ((char*)buf)[bufferIndex];
		//char* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(indexOfPad, PACKET_LENGTH);
		//char* mac = sha-256(concat(toSend, key));
		char* mac = sha_256(concat(toSend, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		//char* message = concat(toSend, mac);
		char* message = concat(toSend, mac, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH);
		//char* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(indexOfPad, PACKET_LENGTH);
		//send xor(message, pad) to reciever
		n = write(fd, xorCharArray(message, pad, PACKET_LENGTH), PACKET_LENGTH);
		if (n < 0) {
			delete[] key;
			return -1;
		}
		delete[] key;
		//3
	}
}

// recv command
ssize_t cread(int fd, void *buf, size_t len) {
	//1
	//wait for nonce from sender
	char buffer[PACKET_LENGTH];
	int n;
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	//long indexOfPad;
	//indexOfPad = charArrayToLong(message recieved from sender);
	unsigned long long indexOfPad = charArrayToLong(buffer, PACKET_LENGTH);
	//byte* message = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* message = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
	char* pad = OTP(&indexOfPad, PACKET_LENGTH);
	//byte* reply = xor(message, pad);
	char* reply = xorCharArray(message, pad, PACKET_LENGTH);
	//send reply to sender
	n = write(fd, reply, PACKET_LENGTH);
	if (n < 0) {
		return -1;
	}
	//2
	//2.1
	//recieve ok, if not retry, abort, ignore?
	n = read(fd, buffer, PACKET_LENGTH);
	if (n < 0) {
		//error
		return -1;
	}
	else if (n == 0) {
		//error - no message
		return -1;
	}
	else if(std::strcmp(buffer, "OK") != 0) {
		//error - not ok
		return -1;
	}
	//2.2
	//int amount_recv = 0;
	int amount_recv = 0;
	//while(more to recieve or amount_recv + PACKET_DATA_LENGTH < len) {
	while(amount_recv + PACKET_DATA_LENGTH < len) {
		//3
		//byte data[PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH] = message recieved from sender
		char data[PACKET_LENGTH];
		amount_recv += read(fd, data, PACKET_LENGTH);
		//byte* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* key = OTP(&indexOfPad, PACKET_LENGTH);
		//pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH);
		char* pad = OTP(&indexOfPad, PACKET_LENGTH);
		//byte* messsage = xor(data, pad);
		char* message = xorCharArray(data, pad, PACKET_LENGTH);
		//byte* checksum = data + PACKET_DATA_LENGTH;     checksum is last part after the data
		char* checksum = message + PACKET_DATA_LENGTH;
		//byte* mac = sha-256(concat(messsage, key));     recompute mac
		//std::string msgStr(message);
		//std::string keyStr(key);
		char* mac = sha_256(concat(message, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH));
		if(!charArrayEquals(checksum, mac, PACKET_LENGTH)) {
			//checksum != mac
			delete[] mac;
			return -1;
		}

		//copy message into buffer
		for(int i = 0; i < PACKET_DATA_LENGTH; i++) {
			buf[i] = message[i];
		}
		buf += PACKET_DATA_LENGTH;
		delete[] mac;
	}
	return amount_recv;
}

char* OTP(unsigned long long* index, const unsigned long long amount) {
	std::ifstream pad;
	pad.open("otp.key");
	pad.seekg(*index);
	char* result = new char[amount];
	pad.read(result, amount);
	pad.close();
	*index += amount;
	return result;
	//byte pad[amount];  allocate amount bytes to return
	//seek to index in OTP
	//for(long i = 0; i < amount; i++)
		//pad[i] = readByte();  read in each byte from the file
	//*index += amount;  increment index so we don't use the same pad twice
	//return pad;
}

char* xorCharArray(const char* first, const char* second, unsigned long long length) {
	//byte result[length];
	char* result = new char[length];
	//for(long i = 0; i < length; i++) {
	for(unsigned long long i = 0; i < length; i++) {
		result[i] = first[i] ^ second[i];
	}
	return result;
}

unsigned long long unsignedLongLongRand() {
    unsigned long long rand1 = abs(rand());
    unsigned long long rand2 = abs(rand());
    rand1 <<= (sizeof(int)*8);
    unsigned long long randULL = (rand1 | rand2);
    return randULL;
}

char* longToCharArray(unsigned long long num, int size) {
	return reinterpret_cast<char*>(num);
}

unsigned long long charArrayToLong(const char* data, int size){
	return reinterpret_cast<unsigned long long>(data);
}

bool charArrayEquals(const char* data1, const char* data2, int size) {
	for(int i = 0; i < size; i++) {
		if(data1[i] != data2[i]) return false;
	}
	return true;
}

char* concat(const char* left, const char* right, int sizel, int sizer) {
	char* result = new char[sizel + sizer];
	for(int i = 0; i < sizel; i++) {
		result[i] = left[i];
	}
	for(int i = 0; i < sizer; i++) {
		result[sizel + i] = right[i];
	}
	return result;
	//std::string msgStr(left);
	//std::string keyStr(right);
	//return &(left + right)[0];
}

char* sha_256(char* buf) {
	return &sha256(buf)[0];
}
<|endoftext|>


<commit_before><commit_msg>Adicionada questão da 1195 da árvore binária.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix crash on max num point lights change<commit_after><|endoftext|>


<commit_before>#include <iostream>

#include "headings.h"
#include "libaps.h"
#include "constants.h"

#include <concol.h>

using namespace std;

// command options functions taken from:
// http://stackoverflow.com/questions/865668/parse-command-line-arguments
string getCmdOption(char ** begin, char ** end, const std::string & option)
{
  char ** itr = std::find(begin, end, option);
  if (itr != end && ++itr != end)
  {
    return string(*itr);
  }
  return "";
}

bool cmdOptionExists(char** begin, char** end, const std::string& option)
{
  return std::find(begin, end, option) != end;
}

int main (int argc, char* argv[])
{

  concol::concolinit();
  cout << concol::RED << "BBN AP2 Flash Test Executable" << concol::RESET << endl;

  int dbgLevel = 8;
  if (argc >= 2) {
    dbgLevel = atoi(argv[1]);
  }

  set_logging_level(dbgLevel);

  cout << concol::RED << "Attempting to initialize libaps" << concol::RESET << endl;

  init("eth0");

  int numDevices = get_numDevices();

  cout << concol::RED << numDevices << " APS device" << (numDevices > 1 ? "s": "")  << " found" << concol::RESET << endl;

  if (numDevices < 1)
  	return 0;

  cout << concol::RED << "Attempting to get serials" << concol::RESET << endl;

  const char ** serialBuffer = new const char*[numDevices];
  get_deviceSerials(serialBuffer);

  for (int cnt=0; cnt < numDevices; cnt++) {
  	cout << concol::RED << "Device " << cnt << " serial #: " << serialBuffer[cnt] << concol::RESET << endl;
  }

  cout << concol::RED << "Connecting to device serial #: " << serialBuffer[0] << concol::RESET << endl;

  string deviceSerial(serialBuffer[0]);

  connect_APS(deviceSerial.c_str());

  double uptime = get_uptime(deviceSerial.c_str());

  cout << concol::RED << "Uptime for device " << deviceSerial << " is " << uptime << " seconds" << concol::RESET << endl;

  uint32_t buffer[2] = {0, 0};

  // test reading from FLASH
  read_flash(deviceSerial.c_str(), 0x00FF0000, 2, buffer);
  cout << "Programmed MAC address at 0x00FF0000 is " << endl << hexn<8> << buffer[0] << " " << buffer[1] << endl;

  // read SPI setup sequence
  uint32_t setup[32];
  read_flash(deviceSerial.c_str(), 0x0, 32, setup);
  cout << "Programmed setup SPI sequence:" << endl;
  for (size_t ct=0; ct < 32; ct++) {
    cout << hexn<8> << setup[ct] << " ";
    if (ct % 4 == 3) cout << endl;
  }

  // write new SPI setup sequence
  // write_SPI_setup(deviceSerial.c_str());

  cout << concol::RED << "Reading flash addr 0x00FA0000" << concol::RESET << endl;
  read_flash(deviceSerial.c_str(), 0x00FA0000, 2, buffer);
  cout << "Received " << hexn<8> << buffer[0] << " " << hexn<8> << buffer[1] << endl;

  cout << concol::RED << "Erasing/writing flash addr 0x00FA0000" << concol::RESET << endl;
  vector<uint32_t> testData;
  for (size_t ct=0; ct<64; ct++){
    testData.push_back(0x00FA0000 + static_cast<uint32_t>(ct));
  }
  // buffer[0] = 0xBADDF00F;
  write_flash(deviceSerial.c_str(), 0x00FA0000, testData.data(), testData.size());

  cout << concol::RED << "Reading flash addr 0x00FA0000" << concol::RESET << endl;
  read_flash(deviceSerial.c_str(), 0x00FA0000, 2, buffer);
  cout << "Received " << hexn<8> << buffer[0] << " " <<  hexn<8> << buffer[1] << endl;

  disconnect_APS(deviceSerial.c_str());

  delete[] serialBuffer;

  cout << concol::RED << "Finished!" << concol::RESET << endl;

  return 0;
}
<commit_msg>Add 2 word write to flash test.<commit_after>#include <iostream>

#include "headings.h"
#include "libaps.h"
#include "constants.h"

#include <concol.h>

using namespace std;

// command options functions taken from:
// http://stackoverflow.com/questions/865668/parse-command-line-arguments
string getCmdOption(char ** begin, char ** end, const std::string & option)
{
  char ** itr = std::find(begin, end, option);
  if (itr != end && ++itr != end)
  {
    return string(*itr);
  }
  return "";
}

bool cmdOptionExists(char** begin, char** end, const std::string& option)
{
  return std::find(begin, end, option) != end;
}

int main (int argc, char* argv[])
{

  concol::concolinit();
  cout << concol::RED << "BBN AP2 Flash Test Executable" << concol::RESET << endl;

  int dbgLevel = 8;
  if (argc >= 2) {
    dbgLevel = atoi(argv[1]);
  }

  set_logging_level(dbgLevel);

  cout << concol::RED << "Attempting to initialize libaps" << concol::RESET << endl;

  init("eth0");

  int numDevices = get_numDevices();

  cout << concol::RED << numDevices << " APS device" << (numDevices > 1 ? "s": "")  << " found" << concol::RESET << endl;

  if (numDevices < 1)
  	return 0;

  cout << concol::RED << "Attempting to get serials" << concol::RESET << endl;

  const char ** serialBuffer = new const char*[numDevices];
  get_deviceSerials(serialBuffer);

  for (int cnt=0; cnt < numDevices; cnt++) {
  	cout << concol::RED << "Device " << cnt << " serial #: " << serialBuffer[cnt] << concol::RESET << endl;
  }

  cout << concol::RED << "Connecting to device serial #: " << serialBuffer[0] << concol::RESET << endl;

  string deviceSerial(serialBuffer[0]);

  connect_APS(deviceSerial.c_str());

  double uptime = get_uptime(deviceSerial.c_str());

  cout << concol::RED << "Uptime for device " << deviceSerial << " is " << uptime << " seconds" << concol::RESET << endl;

  uint32_t buffer[2] = {0, 0};

  // test reading from FLASH
  read_flash(deviceSerial.c_str(), 0x00FF0000, 2, buffer);
  cout << "Programmed MAC address at 0x00FF0000 is " << endl << hexn<8> << buffer[0] << " " << buffer[1] << endl;

  // read SPI setup sequence
  uint32_t setup[32];
  read_flash(deviceSerial.c_str(), 0x0, 32, setup);
  cout << "Programmed setup SPI sequence:" << endl;
  for (size_t ct=0; ct < 32; ct++) {
    cout << hexn<8> << setup[ct] << " ";
    if (ct % 4 == 3) cout << endl;
  }

  // write new SPI setup sequence
  // write_SPI_setup(deviceSerial.c_str());

  cout << concol::RED << "Reading flash addr 0x00FA0000" << concol::RESET << endl;
  read_flash(deviceSerial.c_str(), 0x00FA0000, 2, buffer);
  cout << "Received " << hexn<8> << buffer[0] << " " << hexn<8> << buffer[1] << endl;

  cout << concol::RED << "Erasing/writing flash addr 0x00FA0000 (64 words)" << concol::RESET << endl;
  vector<uint32_t> testData;
  for (size_t ct=0; ct<64; ct++){
    testData.push_back(0x00FA0000 + static_cast<uint32_t>(ct));
  }
  write_flash(deviceSerial.c_str(), 0x00FA0000, testData.data(), testData.size());

  cout << concol::RED << "Reading flash addr 0x00FA0000" << concol::RESET << endl;
  read_flash(deviceSerial.c_str(), 0x00FA0000, 2, buffer);
  cout << "Received " << hexn<8> << buffer[0] << " " <<  hexn<8> << buffer[1] << endl;

  cout << concol::RED << "Erasing/writing flash addr 0x00FA0000 (2 words)" << concol::RESET << endl;
  buffer[0] = 0xBADD1234;
  buffer[1] = 0x1234F00F;
  write_flash(deviceSerial.c_str(), 0x00FA0000, buffer, 2);

  cout << concol::RED << "Reading flash addr 0x00FA0000" << concol::RESET << endl;
  read_flash(deviceSerial.c_str(), 0x00FA0000, 2, buffer);
  cout << "Received " << hexn<8> << buffer[0] << " " <<  hexn<8> << buffer[1] << endl;

  disconnect_APS(deviceSerial.c_str());

  delete[] serialBuffer;

  cout << concol::RED << "Finished!" << concol::RESET << endl;

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/ssl_config_service.h"

#include "net/base/ssl_config_service_defaults.h"
#include "net/base/ssl_false_start_blacklist.h"

namespace net {

SSLConfig::CertAndStatus::CertAndStatus() : cert_status(0) {}

SSLConfig::CertAndStatus::~CertAndStatus() {}

SSLConfig::SSLConfig()
    : rev_checking_enabled(true), ssl3_enabled(true),
      tls1_enabled(true),
      dns_cert_provenance_checking_enabled(false), cached_info_enabled(false),
      origin_bound_certs_enabled(false),
      false_start_enabled(true),
      send_client_cert(false), verify_ev_cert(false), ssl3_fallback(false) {
}

SSLConfig::~SSLConfig() {
}

bool SSLConfig::IsAllowedBadCert(X509Certificate* cert,
                                 CertStatus* cert_status) const {
  std::string der_cert;
  if (!cert->GetDEREncoded(&der_cert))
    return false;
  return IsAllowedBadCert(der_cert, cert_status);
}

bool SSLConfig::IsAllowedBadCert(const base::StringPiece& der_cert,
                                 CertStatus* cert_status) const {
  for (size_t i = 0; i < allowed_bad_certs.size(); ++i) {
    if (der_cert == allowed_bad_certs[i].der_cert) {
      if (cert_status)
        *cert_status = allowed_bad_certs[i].cert_status;
      return true;
    }
  }
  return false;
}

SSLConfigService::SSLConfigService()
    : observer_list_(ObserverList<Observer>::NOTIFY_EXISTING_ONLY) {
}

// static
bool SSLConfigService::IsKnownFalseStartIncompatibleServer(
    const std::string& hostname) {
  return SSLFalseStartBlacklist::IsMember(hostname);
}

static bool g_cached_info_enabled = false;
static bool g_origin_bound_certs_enabled = false;
static bool g_false_start_enabled = true;
static bool g_dns_cert_provenance_checking = false;

// static
void SSLConfigService::DisableFalseStart() {
  g_false_start_enabled = false;
}

// static
bool SSLConfigService::false_start_enabled() {
  return g_false_start_enabled;
}

// static
void SSLConfigService::EnableDNSCertProvenanceChecking() {
  g_dns_cert_provenance_checking = true;
}

// static
bool SSLConfigService::dns_cert_provenance_checking_enabled() {
  return g_dns_cert_provenance_checking;
}

// static
void SSLConfigService::SetCRLSet(scoped_refptr<CRLSet> crl_set) {
  // TODO(agl): not implemented yet.
}

// static
scoped_refptr<CRLSet> SSLConfigService::GetCRLSet() {
  // TODO(agl): not implemented yet.
  scoped_refptr<CRLSet> ret;
  return ret;
}

void SSLConfigService::EnableCachedInfo() {
  g_cached_info_enabled = true;
}

// static
bool SSLConfigService::cached_info_enabled() {
  return g_cached_info_enabled;
}

// static
void SSLConfigService::EnableOriginBoundCerts() {
  g_origin_bound_certs_enabled = true;
}

// static
bool SSLConfigService::origin_bound_certs_enabled() {
  return g_origin_bound_certs_enabled;
}

void SSLConfigService::AddObserver(Observer* observer) {
  observer_list_.AddObserver(observer);
}

void SSLConfigService::RemoveObserver(Observer* observer) {
  observer_list_.RemoveObserver(observer);
}

SSLConfigService::~SSLConfigService() {
}

// static
void SSLConfigService::SetSSLConfigFlags(SSLConfig* ssl_config) {
  ssl_config->false_start_enabled = g_false_start_enabled;
  ssl_config->dns_cert_provenance_checking_enabled =
      g_dns_cert_provenance_checking;
  ssl_config->cached_info_enabled = g_cached_info_enabled;
  ssl_config->origin_bound_certs_enabled = g_origin_bound_certs_enabled;
}

void SSLConfigService::ProcessConfigUpdate(const SSLConfig& orig_config,
                                           const SSLConfig& new_config) {
  bool config_changed =
      (orig_config.rev_checking_enabled != new_config.rev_checking_enabled) ||
      (orig_config.ssl3_enabled != new_config.ssl3_enabled) ||
      (orig_config.tls1_enabled != new_config.tls1_enabled) ||
      (orig_config.disabled_cipher_suites.size() !=
       new_config.disabled_cipher_suites.size());
  if (!config_changed) {
    config_changed = (orig_config.disabled_cipher_suites !=
        new_config.disabled_cipher_suites);
  }

  if (config_changed)
    FOR_EACH_OBSERVER(Observer, observer_list_, OnSSLConfigChanged());
}

// static
bool SSLConfigService::IsSNIAvailable(SSLConfigService* service) {
  if (!service)
    return false;

  SSLConfig ssl_config;
  service->GetSSLConfig(&ssl_config);
  return ssl_config.tls1_enabled;
}

}  // namespace net
<commit_msg>Simplify a comparison for disabled cipher suites in SSLConfigService<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/ssl_config_service.h"

#include "net/base/ssl_config_service_defaults.h"
#include "net/base/ssl_false_start_blacklist.h"

namespace net {

SSLConfig::CertAndStatus::CertAndStatus() : cert_status(0) {}

SSLConfig::CertAndStatus::~CertAndStatus() {}

SSLConfig::SSLConfig()
    : rev_checking_enabled(true), ssl3_enabled(true),
      tls1_enabled(true),
      dns_cert_provenance_checking_enabled(false), cached_info_enabled(false),
      origin_bound_certs_enabled(false),
      false_start_enabled(true),
      send_client_cert(false), verify_ev_cert(false), ssl3_fallback(false) {
}

SSLConfig::~SSLConfig() {
}

bool SSLConfig::IsAllowedBadCert(X509Certificate* cert,
                                 CertStatus* cert_status) const {
  std::string der_cert;
  if (!cert->GetDEREncoded(&der_cert))
    return false;
  return IsAllowedBadCert(der_cert, cert_status);
}

bool SSLConfig::IsAllowedBadCert(const base::StringPiece& der_cert,
                                 CertStatus* cert_status) const {
  for (size_t i = 0; i < allowed_bad_certs.size(); ++i) {
    if (der_cert == allowed_bad_certs[i].der_cert) {
      if (cert_status)
        *cert_status = allowed_bad_certs[i].cert_status;
      return true;
    }
  }
  return false;
}

SSLConfigService::SSLConfigService()
    : observer_list_(ObserverList<Observer>::NOTIFY_EXISTING_ONLY) {
}

// static
bool SSLConfigService::IsKnownFalseStartIncompatibleServer(
    const std::string& hostname) {
  return SSLFalseStartBlacklist::IsMember(hostname);
}

static bool g_cached_info_enabled = false;
static bool g_origin_bound_certs_enabled = false;
static bool g_false_start_enabled = true;
static bool g_dns_cert_provenance_checking = false;

// static
void SSLConfigService::DisableFalseStart() {
  g_false_start_enabled = false;
}

// static
bool SSLConfigService::false_start_enabled() {
  return g_false_start_enabled;
}

// static
void SSLConfigService::EnableDNSCertProvenanceChecking() {
  g_dns_cert_provenance_checking = true;
}

// static
bool SSLConfigService::dns_cert_provenance_checking_enabled() {
  return g_dns_cert_provenance_checking;
}

// static
void SSLConfigService::SetCRLSet(scoped_refptr<CRLSet> crl_set) {
  // TODO(agl): not implemented yet.
}

// static
scoped_refptr<CRLSet> SSLConfigService::GetCRLSet() {
  // TODO(agl): not implemented yet.
  scoped_refptr<CRLSet> ret;
  return ret;
}

void SSLConfigService::EnableCachedInfo() {
  g_cached_info_enabled = true;
}

// static
bool SSLConfigService::cached_info_enabled() {
  return g_cached_info_enabled;
}

// static
void SSLConfigService::EnableOriginBoundCerts() {
  g_origin_bound_certs_enabled = true;
}

// static
bool SSLConfigService::origin_bound_certs_enabled() {
  return g_origin_bound_certs_enabled;
}

void SSLConfigService::AddObserver(Observer* observer) {
  observer_list_.AddObserver(observer);
}

void SSLConfigService::RemoveObserver(Observer* observer) {
  observer_list_.RemoveObserver(observer);
}

SSLConfigService::~SSLConfigService() {
}

// static
void SSLConfigService::SetSSLConfigFlags(SSLConfig* ssl_config) {
  ssl_config->false_start_enabled = g_false_start_enabled;
  ssl_config->dns_cert_provenance_checking_enabled =
      g_dns_cert_provenance_checking;
  ssl_config->cached_info_enabled = g_cached_info_enabled;
  ssl_config->origin_bound_certs_enabled = g_origin_bound_certs_enabled;
}

void SSLConfigService::ProcessConfigUpdate(const SSLConfig& orig_config,
                                           const SSLConfig& new_config) {
  bool config_changed =
      (orig_config.rev_checking_enabled != new_config.rev_checking_enabled) ||
      (orig_config.ssl3_enabled != new_config.ssl3_enabled) ||
      (orig_config.tls1_enabled != new_config.tls1_enabled) ||
      (orig_config.disabled_cipher_suites !=
       new_config.disabled_cipher_suites);

  if (config_changed)
    FOR_EACH_OBSERVER(Observer, observer_list_, OnSSLConfigChanged());
}

// static
bool SSLConfigService::IsSNIAvailable(SSLConfigService* service) {
  if (!service)
    return false;

  SSLConfig ssl_config;
  service->GetSSLConfig(&ssl_config);
  return ssl_config.tls1_enabled;
}

}  // namespace net
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/socket/socket_test_util.h"

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "net/base/ssl_info.h"
#include "net/socket/socket.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

MockClientSocket::MockClientSocket()
    : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
      callback_(NULL),
      connected_(false) {
}

void MockClientSocket::GetSSLInfo(net::SSLInfo* ssl_info) {
  NOTREACHED();
}

void MockClientSocket::GetSSLCertRequestInfo(
    net::SSLCertRequestInfo* cert_request_info) {
  NOTREACHED();
}

void MockClientSocket::Disconnect() {
  connected_ = false;
  callback_ = NULL;
}

bool MockClientSocket::IsConnected() const {
  return connected_;
}

bool MockClientSocket::IsConnectedAndIdle() const {
  return connected_;
}

#if defined(OS_LINUX)
int MockClientSocket::GetPeerName(struct sockaddr *name, socklen_t *namelen) {
  memset(reinterpret_cast<char *>(name), 0, *namelen);
  return net::OK;
}
#endif  // defined(OS_LINUX)

void MockClientSocket::RunCallbackAsync(net::CompletionCallback* callback,
                                        int result) {
  callback_ = callback;
  MessageLoop::current()->PostTask(FROM_HERE,
      method_factory_.NewRunnableMethod(
          &MockClientSocket::RunCallback, result));
}

void MockClientSocket::RunCallback(int result) {
  net::CompletionCallback* c = callback_;
  callback_ = NULL;
  if (c)
    c->Run(result);
}

MockTCPClientSocket::MockTCPClientSocket(const net::AddressList& addresses,
                                         net::MockSocket* socket)
    : addresses_(addresses),
      data_(socket),
      read_offset_(0),
      read_data_(true, net::ERR_UNEXPECTED),
      need_read_data_(true) {
  DCHECK(data_);
  data_->Reset();
}

int MockTCPClientSocket::Connect(net::CompletionCallback* callback) {
  DCHECK(!callback_);
  if (connected_)
    return net::OK;
  connected_ = true;
  if (data_->connect_data().async) {
    RunCallbackAsync(callback, data_->connect_data().result);
    return net::ERR_IO_PENDING;
  }
  return data_->connect_data().result;
}

int MockTCPClientSocket::Read(net::IOBuffer* buf, int buf_len,
                              net::CompletionCallback* callback) {
  DCHECK(!callback_);

  if (!IsConnected())
    return net::ERR_UNEXPECTED;

  if (need_read_data_) {
    read_data_ = data_->GetNextRead();
    need_read_data_ = false;
  }
  int result = read_data_.result;
  if (read_data_.data) {
    if (read_data_.data_len - read_offset_ > 0) {
      result = std::min(buf_len, read_data_.data_len - read_offset_);
      memcpy(buf->data(), read_data_.data + read_offset_, result);
      read_offset_ += result;
      if (read_offset_ == read_data_.data_len) {
        need_read_data_ = true;
        read_offset_ = 0;
      }
    } else {
      result = 0;  // EOF
    }
  }
  if (read_data_.async) {
    RunCallbackAsync(callback, result);
    return net::ERR_IO_PENDING;
  }
  return result;
}

int MockTCPClientSocket::Write(net::IOBuffer* buf, int buf_len,
                               net::CompletionCallback* callback) {
  DCHECK(buf);
  DCHECK(buf_len > 0);
  DCHECK(!callback_);

  if (!IsConnected())
    return net::ERR_UNEXPECTED;

  std::string data(buf->data(), buf_len);
  net::MockWriteResult write_result = data_->OnWrite(data);

  if (write_result.async) {
    RunCallbackAsync(callback, write_result.result);
    return net::ERR_IO_PENDING;
  }
  return write_result.result;
}

class MockSSLClientSocket::ConnectCallback :
    public net::CompletionCallbackImpl<MockSSLClientSocket::ConnectCallback> {
 public:
  ConnectCallback(MockSSLClientSocket *ssl_client_socket,
                  net::CompletionCallback* user_callback,
                  int rv)
      : ALLOW_THIS_IN_INITIALIZER_LIST(
          net::CompletionCallbackImpl<MockSSLClientSocket::ConnectCallback>(
                this, &ConnectCallback::Wrapper)),
        ssl_client_socket_(ssl_client_socket),
        user_callback_(user_callback),
        rv_(rv) {
  }

 private:
  void Wrapper(int rv) {
    if (rv_ == net::OK)
      ssl_client_socket_->connected_ = true;
    user_callback_->Run(rv_);
    delete this;
  }

  MockSSLClientSocket* ssl_client_socket_;
  net::CompletionCallback* user_callback_;
  int rv_;
};

MockSSLClientSocket::MockSSLClientSocket(
    net::ClientSocket* transport_socket,
    const std::string& hostname,
    const net::SSLConfig& ssl_config,
    net::MockSSLSocket* socket)
    : transport_(transport_socket),
      data_(socket) {
  DCHECK(data_);
}

MockSSLClientSocket::~MockSSLClientSocket() {
  Disconnect();
}

void MockSSLClientSocket::GetSSLInfo(net::SSLInfo* ssl_info) {
  ssl_info->Reset();
}

int MockSSLClientSocket::Connect(net::CompletionCallback* callback) {
  DCHECK(!callback_);
  ConnectCallback* connect_callback = new ConnectCallback(
      this, callback, data_->connect.result);
  int rv = transport_->Connect(connect_callback);
  if (rv == net::OK) {
    delete connect_callback;
    if (data_->connect.async) {
      RunCallbackAsync(callback, data_->connect.result);
      return net::ERR_IO_PENDING;
    }
    if (data_->connect.result == net::OK)
      connected_ = true;
    return data_->connect.result;
  }
  return rv;
}

void MockSSLClientSocket::Disconnect() {
  MockClientSocket::Disconnect();
  if (transport_ != NULL)
    transport_->Disconnect();
}

int MockSSLClientSocket::Read(net::IOBuffer* buf, int buf_len,
                              net::CompletionCallback* callback) {
  DCHECK(!callback_);
  return transport_->Read(buf, buf_len, callback);
}

int MockSSLClientSocket::Write(net::IOBuffer* buf, int buf_len,
                               net::CompletionCallback* callback) {
  DCHECK(!callback_);
  return transport_->Write(buf, buf_len, callback);
}

MockRead StaticMockSocket::GetNextRead() {
  return reads_[read_index_++];
}

MockWriteResult StaticMockSocket::OnWrite(const std::string& data) {
  if (!writes_) {
    // Not using mock writes; succeed synchronously.
    return MockWriteResult(false, data.length());
  }

  // Check that what we are writing matches the expectation.
  // Then give the mocked return value.
  net::MockWrite* w = &writes_[write_index_++];
  int result = w->result;
  if (w->data) {
    std::string expected_data(w->data, w->data_len);
    EXPECT_EQ(expected_data, data);
    if (expected_data != data)
      return MockWriteResult(false, net::ERR_UNEXPECTED);
    if (result == net::OK)
      result = w->data_len;
  }
  return MockWriteResult(w->async, result);
}

void StaticMockSocket::Reset() {
  read_index_ = 0;
  write_index_ = 0;
}

DynamicMockSocket::DynamicMockSocket()
    : short_read_limit_(0),
      allow_unconsumed_reads_(false) {
}

MockRead DynamicMockSocket::GetNextRead() {
  if (reads_.empty())
    return MockRead(true, ERR_UNEXPECTED);
  MockRead result = reads_.front();
  if (short_read_limit_ == 0 || result.data_len <= short_read_limit_) {
    reads_.pop_front();
  } else {
    result.data_len = short_read_limit_;
    reads_.front().data += result.data_len;
    reads_.front().data_len -= result.data_len;
  }
  return result;
}

void DynamicMockSocket::Reset() {
  reads_.clear();
}

void DynamicMockSocket::SimulateRead(const char* data) {
  if (!allow_unconsumed_reads_) {
    EXPECT_TRUE(reads_.empty()) << "Unconsumed read: " << reads_.front().data;
  }
  reads_.push_back(MockRead(data));
}

void MockClientSocketFactory::AddMockSocket(MockSocket* socket) {
  mock_sockets_.Add(socket);
}

void MockClientSocketFactory::AddMockSSLSocket(MockSSLSocket* socket) {
  mock_ssl_sockets_.Add(socket);
}

void MockClientSocketFactory::ResetNextMockIndexes() {
  mock_sockets_.ResetNextIndex();
  mock_ssl_sockets_.ResetNextIndex();
}

MockTCPClientSocket* MockClientSocketFactory::GetMockTCPClientSocket(
    int index) const {
  return tcp_client_sockets_[index];
}

MockSSLClientSocket* MockClientSocketFactory::GetMockSSLClientSocket(
    int index) const {
  return ssl_client_sockets_[index];
}

ClientSocket* MockClientSocketFactory::CreateTCPClientSocket(
    const AddressList& addresses) {
  MockTCPClientSocket* socket =
      new MockTCPClientSocket(addresses, mock_sockets_.GetNext());
  tcp_client_sockets_.push_back(socket);
  return socket;
}

SSLClientSocket* MockClientSocketFactory::CreateSSLClientSocket(
    ClientSocket* transport_socket,
    const std::string& hostname,
    const SSLConfig& ssl_config) {
  MockSSLClientSocket* socket =
      new MockSSLClientSocket(transport_socket, hostname, ssl_config,
                              mock_ssl_sockets_.GetNext());
  ssl_client_sockets_.push_back(socket);
  return socket;
}

int TestSocketRequest::WaitForResult() {
  return callback_.WaitForResult();
}

void TestSocketRequest::RunWithParams(const Tuple1<int>& params) {
  callback_.RunWithParams(params);
  (*completion_count_)++;
  request_order_->push_back(this);
}

// static
const int ClientSocketPoolTest::kIndexOutOfBounds = -1;

// static
const int ClientSocketPoolTest::kRequestNotFound = -2;

void ClientSocketPoolTest::SetUp() {
  completion_count_ = 0;
}

void ClientSocketPoolTest::TearDown() {
  // The tests often call Reset() on handles at the end which may post
  // DoReleaseSocket() tasks.
  MessageLoop::current()->RunAllPending();
}

int ClientSocketPoolTest::GetOrderOfRequest(size_t index) {
  index--;
  if (index < 0 || index >= requests_.size())
    return kIndexOutOfBounds;

  for (size_t i = 0; i < request_order_.size(); i++)
    if (requests_[index] == request_order_[i])
      return i + 1;

  return kRequestNotFound;
}

bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive) {
  ScopedVector<TestSocketRequest>::iterator i;
  for (i = requests_.begin(); i != requests_.end(); ++i) {
    if ((*i)->handle()->is_initialized()) {
      if (keep_alive == NO_KEEP_ALIVE)
        (*i)->handle()->socket()->Disconnect();
      (*i)->handle()->Reset();
      MessageLoop::current()->RunAllPending();
      return true;
    }
  }
  return false;
}

void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
  bool released_one;
  do {
    released_one = ReleaseOneConnection(keep_alive);
  } while (released_one);
}

}  // namespace net
<commit_msg>Coverity: Remove a check for index < 0 because index is size_t and can never be < 0.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/socket/socket_test_util.h"

#include <algorithm>

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "net/base/ssl_info.h"
#include "net/socket/socket.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

MockClientSocket::MockClientSocket()
    : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
      callback_(NULL),
      connected_(false) {
}

void MockClientSocket::GetSSLInfo(net::SSLInfo* ssl_info) {
  NOTREACHED();
}

void MockClientSocket::GetSSLCertRequestInfo(
    net::SSLCertRequestInfo* cert_request_info) {
  NOTREACHED();
}

void MockClientSocket::Disconnect() {
  connected_ = false;
  callback_ = NULL;
}

bool MockClientSocket::IsConnected() const {
  return connected_;
}

bool MockClientSocket::IsConnectedAndIdle() const {
  return connected_;
}

#if defined(OS_LINUX)
int MockClientSocket::GetPeerName(struct sockaddr *name, socklen_t *namelen) {
  memset(reinterpret_cast<char *>(name), 0, *namelen);
  return net::OK;
}
#endif  // defined(OS_LINUX)

void MockClientSocket::RunCallbackAsync(net::CompletionCallback* callback,
                                        int result) {
  callback_ = callback;
  MessageLoop::current()->PostTask(FROM_HERE,
      method_factory_.NewRunnableMethod(
          &MockClientSocket::RunCallback, result));
}

void MockClientSocket::RunCallback(int result) {
  net::CompletionCallback* c = callback_;
  callback_ = NULL;
  if (c)
    c->Run(result);
}

MockTCPClientSocket::MockTCPClientSocket(const net::AddressList& addresses,
                                         net::MockSocket* socket)
    : addresses_(addresses),
      data_(socket),
      read_offset_(0),
      read_data_(true, net::ERR_UNEXPECTED),
      need_read_data_(true) {
  DCHECK(data_);
  data_->Reset();
}

int MockTCPClientSocket::Connect(net::CompletionCallback* callback) {
  DCHECK(!callback_);
  if (connected_)
    return net::OK;
  connected_ = true;
  if (data_->connect_data().async) {
    RunCallbackAsync(callback, data_->connect_data().result);
    return net::ERR_IO_PENDING;
  }
  return data_->connect_data().result;
}

int MockTCPClientSocket::Read(net::IOBuffer* buf, int buf_len,
                              net::CompletionCallback* callback) {
  DCHECK(!callback_);

  if (!IsConnected())
    return net::ERR_UNEXPECTED;

  if (need_read_data_) {
    read_data_ = data_->GetNextRead();
    need_read_data_ = false;
  }
  int result = read_data_.result;
  if (read_data_.data) {
    if (read_data_.data_len - read_offset_ > 0) {
      result = std::min(buf_len, read_data_.data_len - read_offset_);
      memcpy(buf->data(), read_data_.data + read_offset_, result);
      read_offset_ += result;
      if (read_offset_ == read_data_.data_len) {
        need_read_data_ = true;
        read_offset_ = 0;
      }
    } else {
      result = 0;  // EOF
    }
  }
  if (read_data_.async) {
    RunCallbackAsync(callback, result);
    return net::ERR_IO_PENDING;
  }
  return result;
}

int MockTCPClientSocket::Write(net::IOBuffer* buf, int buf_len,
                               net::CompletionCallback* callback) {
  DCHECK(buf);
  DCHECK_GT(buf_len, 0);
  DCHECK(!callback_);

  if (!IsConnected())
    return net::ERR_UNEXPECTED;

  std::string data(buf->data(), buf_len);
  net::MockWriteResult write_result = data_->OnWrite(data);

  if (write_result.async) {
    RunCallbackAsync(callback, write_result.result);
    return net::ERR_IO_PENDING;
  }
  return write_result.result;
}

class MockSSLClientSocket::ConnectCallback :
    public net::CompletionCallbackImpl<MockSSLClientSocket::ConnectCallback> {
 public:
  ConnectCallback(MockSSLClientSocket *ssl_client_socket,
                  net::CompletionCallback* user_callback,
                  int rv)
      : ALLOW_THIS_IN_INITIALIZER_LIST(
          net::CompletionCallbackImpl<MockSSLClientSocket::ConnectCallback>(
                this, &ConnectCallback::Wrapper)),
        ssl_client_socket_(ssl_client_socket),
        user_callback_(user_callback),
        rv_(rv) {
  }

 private:
  void Wrapper(int rv) {
    if (rv_ == net::OK)
      ssl_client_socket_->connected_ = true;
    user_callback_->Run(rv_);
    delete this;
  }

  MockSSLClientSocket* ssl_client_socket_;
  net::CompletionCallback* user_callback_;
  int rv_;
};

MockSSLClientSocket::MockSSLClientSocket(
    net::ClientSocket* transport_socket,
    const std::string& hostname,
    const net::SSLConfig& ssl_config,
    net::MockSSLSocket* socket)
    : transport_(transport_socket),
      data_(socket) {
  DCHECK(data_);
}

MockSSLClientSocket::~MockSSLClientSocket() {
  Disconnect();
}

void MockSSLClientSocket::GetSSLInfo(net::SSLInfo* ssl_info) {
  ssl_info->Reset();
}

int MockSSLClientSocket::Connect(net::CompletionCallback* callback) {
  DCHECK(!callback_);
  ConnectCallback* connect_callback = new ConnectCallback(
      this, callback, data_->connect.result);
  int rv = transport_->Connect(connect_callback);
  if (rv == net::OK) {
    delete connect_callback;
    if (data_->connect.async) {
      RunCallbackAsync(callback, data_->connect.result);
      return net::ERR_IO_PENDING;
    }
    if (data_->connect.result == net::OK)
      connected_ = true;
    return data_->connect.result;
  }
  return rv;
}

void MockSSLClientSocket::Disconnect() {
  MockClientSocket::Disconnect();
  if (transport_ != NULL)
    transport_->Disconnect();
}

int MockSSLClientSocket::Read(net::IOBuffer* buf, int buf_len,
                              net::CompletionCallback* callback) {
  DCHECK(!callback_);
  return transport_->Read(buf, buf_len, callback);
}

int MockSSLClientSocket::Write(net::IOBuffer* buf, int buf_len,
                               net::CompletionCallback* callback) {
  DCHECK(!callback_);
  return transport_->Write(buf, buf_len, callback);
}

MockRead StaticMockSocket::GetNextRead() {
  return reads_[read_index_++];
}

MockWriteResult StaticMockSocket::OnWrite(const std::string& data) {
  if (!writes_) {
    // Not using mock writes; succeed synchronously.
    return MockWriteResult(false, data.length());
  }

  // Check that what we are writing matches the expectation.
  // Then give the mocked return value.
  net::MockWrite* w = &writes_[write_index_++];
  int result = w->result;
  if (w->data) {
    std::string expected_data(w->data, w->data_len);
    EXPECT_EQ(expected_data, data);
    if (expected_data != data)
      return MockWriteResult(false, net::ERR_UNEXPECTED);
    if (result == net::OK)
      result = w->data_len;
  }
  return MockWriteResult(w->async, result);
}

void StaticMockSocket::Reset() {
  read_index_ = 0;
  write_index_ = 0;
}

DynamicMockSocket::DynamicMockSocket()
    : short_read_limit_(0),
      allow_unconsumed_reads_(false) {
}

MockRead DynamicMockSocket::GetNextRead() {
  if (reads_.empty())
    return MockRead(true, ERR_UNEXPECTED);
  MockRead result = reads_.front();
  if (short_read_limit_ == 0 || result.data_len <= short_read_limit_) {
    reads_.pop_front();
  } else {
    result.data_len = short_read_limit_;
    reads_.front().data += result.data_len;
    reads_.front().data_len -= result.data_len;
  }
  return result;
}

void DynamicMockSocket::Reset() {
  reads_.clear();
}

void DynamicMockSocket::SimulateRead(const char* data) {
  if (!allow_unconsumed_reads_) {
    EXPECT_TRUE(reads_.empty()) << "Unconsumed read: " << reads_.front().data;
  }
  reads_.push_back(MockRead(data));
}

void MockClientSocketFactory::AddMockSocket(MockSocket* socket) {
  mock_sockets_.Add(socket);
}

void MockClientSocketFactory::AddMockSSLSocket(MockSSLSocket* socket) {
  mock_ssl_sockets_.Add(socket);
}

void MockClientSocketFactory::ResetNextMockIndexes() {
  mock_sockets_.ResetNextIndex();
  mock_ssl_sockets_.ResetNextIndex();
}

MockTCPClientSocket* MockClientSocketFactory::GetMockTCPClientSocket(
    int index) const {
  return tcp_client_sockets_[index];
}

MockSSLClientSocket* MockClientSocketFactory::GetMockSSLClientSocket(
    int index) const {
  return ssl_client_sockets_[index];
}

ClientSocket* MockClientSocketFactory::CreateTCPClientSocket(
    const AddressList& addresses) {
  MockTCPClientSocket* socket =
      new MockTCPClientSocket(addresses, mock_sockets_.GetNext());
  tcp_client_sockets_.push_back(socket);
  return socket;
}

SSLClientSocket* MockClientSocketFactory::CreateSSLClientSocket(
    ClientSocket* transport_socket,
    const std::string& hostname,
    const SSLConfig& ssl_config) {
  MockSSLClientSocket* socket =
      new MockSSLClientSocket(transport_socket, hostname, ssl_config,
                              mock_ssl_sockets_.GetNext());
  ssl_client_sockets_.push_back(socket);
  return socket;
}

int TestSocketRequest::WaitForResult() {
  return callback_.WaitForResult();
}

void TestSocketRequest::RunWithParams(const Tuple1<int>& params) {
  callback_.RunWithParams(params);
  (*completion_count_)++;
  request_order_->push_back(this);
}

// static
const int ClientSocketPoolTest::kIndexOutOfBounds = -1;

// static
const int ClientSocketPoolTest::kRequestNotFound = -2;

void ClientSocketPoolTest::SetUp() {
  completion_count_ = 0;
}

void ClientSocketPoolTest::TearDown() {
  // The tests often call Reset() on handles at the end which may post
  // DoReleaseSocket() tasks.
  MessageLoop::current()->RunAllPending();
}

int ClientSocketPoolTest::GetOrderOfRequest(size_t index) {
  index--;
  if (index >= requests_.size())
    return kIndexOutOfBounds;

  for (size_t i = 0; i < request_order_.size(); i++)
    if (requests_[index] == request_order_[i])
      return i + 1;

  return kRequestNotFound;
}

bool ClientSocketPoolTest::ReleaseOneConnection(KeepAlive keep_alive) {
  ScopedVector<TestSocketRequest>::iterator i;
  for (i = requests_.begin(); i != requests_.end(); ++i) {
    if ((*i)->handle()->is_initialized()) {
      if (keep_alive == NO_KEEP_ALIVE)
        (*i)->handle()->socket()->Disconnect();
      (*i)->handle()->Reset();
      MessageLoop::current()->RunAllPending();
      return true;
    }
  }
  return false;
}

void ClientSocketPoolTest::ReleaseAllConnections(KeepAlive keep_alive) {
  bool released_one;
  do {
    released_one = ReleaseOneConnection(keep_alive);
  } while (released_one);
}

}  // namespace net
<|endoftext|>


<commit_before>//
//  File.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 10/09/2016.
//  Copyright 2016 Thomas Harte. All rights reserved.
//

#include "File.hpp"

bool Analyser::Static::Commodore::File::is_basic() {
	// BASIC files are always relocatable (?)
	if(type != File::RelocatableProgram) return false;

	uint16_t line_address = starting_address;
	int line_number = -1;

	// decide whether this is a BASIC file based on the proposition that:
	//	(1) they're always relocatable; and
	//	(2) they have a per-line structure of:
	//		[4 bytes: address of start of next line]
	//		[4 bytes: this line number]
	//		... null-terminated code ...
	//	(with a next line address of 0000 indicating end of program)ß
	while(1) {
		if(static_cast<size_t>(line_address - starting_address) >= data.size() + 2) break;

		uint16_t next_line_address = data[line_address - starting_address];
		next_line_address |= data[line_address - starting_address + 1] << 8;

		if(!next_line_address) {
			return true;
		}
		if(next_line_address < line_address + 5) break;

		if(static_cast<size_t>(line_address - starting_address) >= data.size() + 5) break;
		uint16_t next_line_number = data[line_address - starting_address + 2];
		next_line_number |= data[line_address - starting_address + 3] << 8;

		if(next_line_number <= line_number) break;

		line_number = static_cast<uint16_t>(next_line_number);
		line_address = next_line_address;
	}

	return false;
}
<commit_msg>Removes stray non-ASCII typo.<commit_after>//
//  File.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 10/09/2016.
//  Copyright 2016 Thomas Harte. All rights reserved.
//

#include "File.hpp"

bool Analyser::Static::Commodore::File::is_basic() {
	// BASIC files are always relocatable (?)
	if(type != File::RelocatableProgram) return false;

	uint16_t line_address = starting_address;
	int line_number = -1;

	// decide whether this is a BASIC file based on the proposition that:
	//	(1) they're always relocatable; and
	//	(2) they have a per-line structure of:
	//		[4 bytes: address of start of next line]
	//		[4 bytes: this line number]
	//		... null-terminated code ...
	//	(with a next line address of 0000 indicating end of program)
	while(1) {
		if(static_cast<size_t>(line_address - starting_address) >= data.size() + 2) break;

		uint16_t next_line_address = data[line_address - starting_address];
		next_line_address |= data[line_address - starting_address + 1] << 8;

		if(!next_line_address) {
			return true;
		}
		if(next_line_address < line_address + 5) break;

		if(static_cast<size_t>(line_address - starting_address) >= data.size() + 5) break;
		uint16_t next_line_number = data[line_address - starting_address + 2];
		next_line_number |= data[line_address - starting_address + 3] << 8;

		if(next_line_number <= line_number) break;

		line_number = static_cast<uint16_t>(next_line_number);
		line_address = next_line_address;
	}

	return false;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>

int main() {
  std::cout << "timeout" << std::endl;
  sleep(2);
}

<commit_msg>fix compilation af test code on windows<commit_after>#include <iostream>
#ifdef _MSC_VER
# include <Windows.h>
#else
# include <unistd.h>
#endif

int main() {
  std::cout << "timeout" << std::endl;
#ifdef _MSC_VER
  Sleep(2000);
#else
  sleep(2);
#endif
}

<|endoftext|>