void CSerialPort::ReadEx(void* lpBuf, DWORD dwCount)
{
  ASSERT(IsOpen());

  OVERLAPPED* pOverlapped = new OVERLAPPED;
  ZeroMemory(pOverlapped, sizeof(OVERLAPPED));
  pOverlapped->hEvent = (HANDLE) this;
  if (!ReadFileEx(m_hComm, lpBuf, dwCount, pOverlapped, _OnCompletion))
  {
    delete pOverlapped;
    TRACE(_T("Failed in call to ReadFileEx\n"));
    AfxThrowSerialException();
  }
}
Example #2
0
/**
 * IOチャネル入力時の処理 
 */
static void fi_input(ioent_t *io, event_t *evt, int exec) {
    DWORD error;

//    printf("fi_input: enter(exec=%d, trans=%d)\n", exec, evt->trans);
//    fflush(stdout);

    if (evt->trans == 0) {
        aio_count++;
        /* 新規に読み込みIO発行 */
        if (!ReadFileEx(io->handle, io->buf, io->bufsz, &io->ctlblk, read_completion_handler)) {
            error = GetLastError();
            switch (error) {
            case ERROR_IO_PENDING:
                break;
            case ERROR_HANDLE_EOF:
                aio_count--;
                io_read_complete(io, 0);
                close_file(io);
                break;
            default:
                perr(PERR_SYSTEM, "ReadFile", StrError(error), __FILE__, __LINE__);
                return;
            }
        }
        return;
    }

    if (!SetEvent(io->ctlblk.hEvent)) {
        error = GetLastError();
        perr(PERR_SYSTEM, "SetEvent", StrError(error), __FILE__, __LINE__);
        return;
    }
    TAILQ_INSERT_TAIL(&__prc__mioq, io, mlink);
}
Example #3
0
static VOID WINAPI global_iface_write_completed(DWORD err, DWORD bytes,
						LPOVERLAPPED overlap)
{
	struct wpa_global_dst *dst = (struct wpa_global_dst *) overlap;
	wpa_printf(MSG_DEBUG, "CTRL: Overlapped write completed: dst=%p "
		   "err=%d bytes=%d", dst, (int) err, (int) bytes);
	if (err) {
		global_close_pipe(dst);
		return;
	}

	os_free(dst->rsp_buf);
	dst->rsp_buf = NULL;

	if (!ReadFileEx(dst->pipe, dst->req_buf, sizeof(dst->req_buf),
			&dst->overlap, global_iface_read_completed)) {
		wpa_printf(MSG_DEBUG, "CTRL: ReadFileEx failed: %d",
			   (int) GetLastError());
		global_close_pipe(dst);
		/* FIX: if this was the pipe waiting for new global
		 * connections, at this point there are no open global pipes..
		 * Should try to open a new pipe.. */
		return;
	}
	wpa_printf(MSG_DEBUG, "CTRL: Overlapped read started for %p", dst);
}
Example #4
0
bool AsyncFile::asyncRead(qint64 pos)
{
    if (reading)
        return true;

    qint64 bytes = qMin(BUFFER_SIZE, MAX_BUFFER_SIZE - m_readBuffer.size());
    const qint64 offset = pos + m_readBuffer.size();
    bytes = qMin(bytes, size() - offset);
    qDebug() << "asyncRead" << "pos" << pos << "size" << size() << "bytes" << bytes;
    if (bytes <= 0)
        return true;
    Q_ASSERT(offset + bytes <= size());
    overlapped.overlapped.Offset = offset;

    bool ok = ReadFileEx(m_FileHandle,
                         overlapped.buffer,
                         bytes,
//                             &dwBytesRead,
                         &overlapped.overlapped,
                         &readCallback);
    if (!ok) {
        setError(QFileDevice::ReadError, errorMessage(GetLastError()) );
    }
    reading = ok;
    qDebug() << "asyncRead" << "finished" << ok;
    return ok;
}
Example #5
0
/*
 * Read-completion routine for interactive service pipe. Call with
 * err = 0, bytes = 0 to queue the first read request.
 */
static void WINAPI
HandleServiceIO (DWORD err, DWORD bytes, LPOVERLAPPED lpo)
{
    service_io_t *s = (service_io_t *) lpo;
    int len, capacity;

    len = _countof(s->readbuf);
    capacity = (len-1)*sizeof(*(s->readbuf));

    if (bytes > 0)
    {
        /* messages from the service are not nul terminated */
        int nchars = bytes/sizeof(s->readbuf[0]);
        s->readbuf[nchars] = L'\0';
        SetEvent (s->hEvent);
    }
    if (err)
    {
        _snwprintf(s->readbuf, len, L"0x%08x\nInteractive Service disconnected\n", err);
        s->readbuf[len-1] = L'\0';
        SetEvent (s->hEvent);
        return;
    }

    /* queue next read request */
    ReadFileEx (s->pipe, s->readbuf, capacity, lpo, HandleServiceIO);
    /* Any error in the above call will get checked in next round */
}
Example #6
0
File: comm.c Project: Kelimion/wine
static void comm_waitread(struct DosDeviceStruct *ptr)
{
	unsigned int bleft;
	COMSTAT stat;

	/* FIXME: get timeouts working properly so we can read bleft bytes */
	bleft = ((ptr->ibuf_tail > ptr->ibuf_head) ?
		(ptr->ibuf_tail-1) : ptr->ibuf_size) - ptr->ibuf_head;

	/* find out how many bytes are left in the buffer */
	if(ClearCommError(ptr->handle,NULL,&stat))
		bleft = (bleft<stat.cbInQue) ? bleft : stat.cbInQue;
	else
		bleft = 1;

	/* always read at least one byte */
	if(bleft==0)
		bleft++;

	ReadFileEx(ptr->handle,
		ptr->inbuf + ptr->ibuf_head,
		bleft,
		&ptr->read_ov,
		COMM16_ReadComplete);
}
Example #7
0
static void overlapped_action(long action, long id,
                              HANDLE fd, char *buf, long len) {
  BOOL res;
  long err;
  completionData * d = GlobalAlloc(GPTR, sizeof(completionData));
  if (d == NULL) {
    errno = ENOMEM;
    uerror(action_name[action], Nothing);
  }
  d->id = id;
  d->action = action;

  D(printf("Starting %s: id %ld, len %ld\n", action_name[action], id, len));
  res =
    (action == READ_OVERLAPPED)?
    ReadFileEx(fd, buf, len, &(d->overlapped), overlapped_completion):
    WriteFileEx(fd, buf, len, &(d->overlapped), overlapped_completion);

  if (!res) {
    err = GetLastError ();
    if (err != ERROR_IO_PENDING) {
      win32_maperr (err);
  D(printf("Action %s failed: id %ld -> err %d (errCode %ld)\n",
           action_name[action], id, errno, err));
      uerror("ReadFileEx", Nothing);
    }
  }
}
void CClientThread::ReadFilePart(HANDLE hFile, const _i64 &offset,const bool &last)
{
	LPOVERLAPPED overlap=new OVERLAPPED;
	//memset(overlap, 0, sizeof(OVERLAPPED) );
	
	overlap->Offset=(DWORD)offset;
	overlap->OffsetHigh=(DWORD)(offset>>32);

	SLPData *ldata=new SLPData;
	ldata->buffer=bufmgr->getBuffer();

	if( ldata->buffer==NULL ) 
	{
		Log("Error: No Free Buffer", LL_DEBUG);
		Log("Info: Free Buffers="+nconvert(bufmgr->nfreeBufffer()), LL_DEBUG );
		return;
	}

	ldata->t_send=&t_send;
	ldata->t_unsend=&t_unsend;
	ldata->last=last;
	ldata->filepart=currfilepart;
	ldata->sendfilepart=&sendfilepart;
	overlap->hEvent=ldata;

	BOOL b=ReadFileEx(hFile, ldata->buffer, READSIZE, overlap, FileIOCompletionRoutine);

	++currfilepart;

	if( /*GetLastError() != ERROR_SUCCESS ||*/ b==false)
	{
		Log("Error: Can't start reading from File", LL_DEBUG);
		return;
	}
}
Example #9
0
DWORD SpecialCases::Sp_ReadFileEx()
		{
		 //HANDLE hFile
    LPVOID lpBuffer = new LPVOID;
    //DWORD nNumberOfBytesToRead,
    LPOVERLAPPED lpOverlapped;
   
    // Allocate a lpOverlapped structure.
    lpOverlapped = (LPOVERLAPPED)LocalAlloc(LMEM_ZEROINIT,sizeof(OVERLAPPED)); 

    HANDLE hFile; 
    
    hFile = CreateFile("ReadMe.TXT",               // open ReadMe.TXT 
                        GENERIC_READ,              // open for reading 
                        FILE_SHARE_READ,           // share for reading 
                        NULL,                      // no security 
                        OPEN_EXISTING,             // existing file only 
                        FILE_ATTRIBUTE_NORMAL,     // normal file 
                        NULL);                     // no attr. template 

    BOOL returnVal_Real = 0;
    BOOL returnVal_Intercepted = 0;
    
    return(ReadFileEx(hFile,lpBuffer,0,lpOverlapped,NULL));
		}
void SpectraVFSCached::Read( size_t _nSpectraIndex, Spectra *_pDestination, bool bAsyncRead )
{
	_cprintf("disk.read\n");
	assert( _pDestination != NULL );

	size_t nBytesToRead = TOTALCACHELINEBYTES;

	// check out of array bounds
	if ( _nSpectraIndex >= m_nNumberOfSpectra )
	{
		assert(0);
		// total missed the bounds -> skip
		return;
	}

	// check for cacheline cropping
	if ( _nSpectraIndex+SpectraVFS::CACHELINESIZE >= m_nNumberOfSpectra )
	{
		// pre condition: _nIndex < m_nNumberOfSpectra 
		nBytesToRead = (m_nNumberOfSpectra-_nSpectraIndex)*SPECTRASIZE;
	}

	DWORD ndwBytesToRead = static_cast<DWORD>(nBytesToRead);

	uint64_t nOffset = static_cast<uint64_t>(_nSpectraIndex)*SPECTRASIZE;
	uint32_t nOffsetLow, nOffsetHigh;
	Helpers::UInt64toHiLow( nOffset, nOffsetLow, nOffsetHigh );
	m_IOHandle.set( nOffsetLow, nOffsetHigh );

	BOOL bReadSuccess = FALSE;

#ifdef SPECTRAVFS_ASYNC_IO
	bReadSuccess = ReadFileEx( m_FileHandle, _pDestination, ndwBytesToRead, &m_IOHandle.m_overlapped, &SpectraVFSCached::ReadFinished );

	if ( !bAsyncRead )
	{
		WaitForIO( m_IOHandle );
	}
#else
	DWORD ndwBytesRead;

	bReadSuccess = ReadFile( m_FileHandle, _pDestination, ndwBytesToRead, &ndwBytesRead, &m_IOHandle.m_overlapped );

	if ( ndwBytesRead != ndwBytesToRead )
	{
		Helpers::print( std::string("SpectraVFSCached::Read Error: not all bytes read.\n"), &m_logFile );
		assert(0);
	}
#endif

	if ( bReadSuccess == FALSE )
	{	
		DWORD err = GetLastError();
		Helpers::print( std::string("SpectraVFSCached::Read Error:")+Helpers::numberToString<DWORD>(err)+std::string("\n"), &m_logFile );
	}
}
Example #11
0
void UserOpenFile()
{

// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = FileWld;
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

// Display the Open dialog box.

if (GetOpenFileName(&ofn)==TRUE)
 {
 GetExtns();		// obtain extension
 hf = CreateFile(ofn.lpstrFile,
                    GENERIC_READ,
                    FILE_SHARE_READ,       // share for reading
                    (LPSECURITY_ATTRIBUTES) NULL,
                    OPEN_EXISTING,         // existing file only
                    FILE_ATTRIBUTE_NORMAL,
                    (HANDLE) NULL);	// address of structure with initialization data
 if(hf==INVALID_HANDLE_VALUE)
  {
     MessageBox(hwnd, "Error! Can not open the file!", "", MB_OK );
  }
 else
  {
    sz = GetFileSize(hf, &Fsz);     // get file size
    if(sz!=INVALID_FILE_SIZE)
    {
    SrcPtr = malloc(sz+1);      // allocate memory
    SrcPtr[sz]=0;

    if( ReadFileEx(hf, SrcPtr, sz, &ol, NULL) )     // read file in buffer
        {
        setText( hwSrcEdit, SrcPtr );   // Set text in Edit control
		ClearListbox(hwKwGrid);
		setText(hwMResEdit,"");		// clear previous
		setText(hwOResEdit,"");
        }
    }
    CloseHandle(hf);
    free(SrcPtr);       // release memory block
  }
 }

}
Example #12
0
BOOLEAN PacketReceivePacket(
  LPADAPTER   AdapterObject,
  LPPACKET    lpPacket,
  BOOLEAN     Sync
)
{
  BOOLEAN      Result;

	lpPacket->OverLapped.Offset=0;
	lpPacket->OverLapped.OffsetHigh=0;
	lpPacket->bIoComplete = FALSE;

#if DEBUG_PACKETS
	D(bug("Packet32: PacketReceivePacket\n"));
#endif

	if (Sync) {
		Result = ReadFile(
							AdapterObject->hFile,
							lpPacket->Buffer,
							lpPacket->Length,
							&lpPacket->BytesReceived,
							&lpPacket->OverLapped
							);
		if(Result) {
			Result = GetOverlappedResult(
									AdapterObject->hFile,
									&lpPacket->OverLapped,
									&lpPacket->BytesReceived,
									TRUE
									);
			if(Result)
				lpPacket->bIoComplete = TRUE;
			else
				lpPacket->free = TRUE;
		}
	} else {
		Result = ReadFileEx(
							AdapterObject->hFile,
							lpPacket->Buffer,
							lpPacket->Length,
							&lpPacket->OverLapped,
							packet_read_completion
							);
	}

	if(!Result) lpPacket->BytesReceived = 0;

#if DEBUG_PACKETS
  D(bug("Packet32: PacketReceivePacket got %d bytes, result=%d\n",lpPacket->BytesReceived,(int)Result));
#endif

  return Result;
}
Example #13
0
	void WINAPI CompletedWriteRoutine(DWORD dwErr,DWORD cbWritten,LPOVERLAPPED lpOverLap){
		LPPIPEINST lpPipeInst;
		BOOL fRead = FALSE;
		lpPipeInst = (LPPIPEINST) lpOverLap;
		if ((dwErr == 0) && (cbWritten == lpPipeInst->cbToWrite)){
			fRead = ReadFileEx(lpPipeInst->hPipeInst,lpPipeInst->chRequest,
			BUFSIZE*sizeof(TCHAR),(LPOVERLAPPED) lpPipeInst,
			(LPOVERLAPPED_COMPLETION_ROUTINE) CompletedReadRoutine);
		}
		if (!fRead) DisconnectAndClose(lpPipeInst);
	}
Example #14
0
bool Connection::AsyncRead(LPOVERLAPPED_COMPLETION_ROUTINE cb) {
  if (disconnecting_ && sending_queue_.empty()) {
    return false;
  }
  ZeroMemory(read_buf_, sizeof read_buf_);
  auto read = ReadFileEx(
    pipe_.get(),
    read_buf_,
    kBufferSize * sizeof read_buf_[0],
    (LPOVERLAPPED)&io_overlap_,
    cb);
  return !!read;
}
Example #15
0
int async_pipe_read(async_pipe_t pipe, void* msg, int len, async_pipe_onread callback, void* param)
{
	Win32Pipe* o = (Win32Pipe*)pipe;
	o->read = callback;
	o->param = param;

	assert(1==InterlockedIncrement(&(o->ref)));
	if(!ReadFileEx(o->pipe, msg, len, &(o->overlap), winpipe_onread))
	{
		assert(0==InterlockedDecrement(&(o->ref)));
		return (int)GetLastError();
	}
	return 0;
}
static int waitRecvPacket(tap_win32 *dev, struct timeval *tv)
{
	int retVal = 0;
	DWORD status;

	EnterCriticalSection(&dev->fLocker);

	if(dev->fReading)
	{
		retVal = -1;
	}
	else if(dev->fBufferLen == 0)
	{
		retVal = -1;

		dev->fReading = TRUE;
		dev->fOverlapped.Internal = 0;
		dev->fOverlapped.InternalHigh = 0;
		dev->fOverlapped.Offset = 0;
		dev->fOverlapped.OffsetHigh = 0;
		dev->fOverlapped.hEvent = dev;
		ResetEvent(dev->fEvent);

		if(ReadFileEx(dev->fHandle, &dev->fBuffer[0], TAP_BUFFER_SIZE,
			      &dev->fOverlapped, waitRecvPacket_callback) == 0)
		{
			ShowErrorMsg("ReadFileEx error");
			dev->fReading = FALSE;
			retVal = -2;
		}
	}

	LeaveCriticalSection(&dev->fLocker);

	if(retVal == -1)
	{
		DWORD timeout = (tv == NULL ? INFINITE : (DWORD)(tv->tv_sec * 1000UL + tv->tv_usec / 1000UL));
		while(TRUE)
		{
			status = WaitForSingleObjectEx(dev->fEvent, timeout, TRUE);
			if(status == WAIT_IO_COMPLETION && tv == NULL) continue;
			if(status == WAIT_OBJECT_0) retVal = 0;
			break;
		}
	}

	return retVal;
}
Example #17
0
void FileReader::readFile(char* filename, LPVOID buffer, OVERLAPPED& ol, uint32& dwBytesRead, uint32 bufferSize) {
    if (DEBUG)
    {
        printf("Reading %s\n", filename);
    }

    bool flag = ReadFileEx(this->hFile, (char*)buffer, bufferSize, &ol, FileIOCompletionRoutine);
    if (DEBUG && !flag)
    {
        //DisplayError(TEXT("ReadFile"));
        printf("Terminal failure: Unable to read from file.\n GetLastError=%08x\n", GetLastError());
        return;
    }
    SleepEx(5000, TRUE);
    dwBytesRead = ol.InternalHigh;
}
Example #18
0
ssize_t win32_fifo_read(void *buf, size_t nbyte){
  int check;
  DWORD re;
  DWORD readbuff;
  DWORD available;
  debug1("Reading pipe handle %p", fifohandle);
  if (!fifohandle) return 0;
  available = win32_fifo_read_peek(NULL);
  if (!available) return 0;
  /* This looks more like a hack than a proper check */
  readbuff = (nbyte > available) ? available : nbyte;
  debug("Starting ReadFileEx");
  check = ReadFileEx(fifohandle,buf,readbuff,&ov1,&ReadComplete);
  WaitForSingleObjectEx(fifohandle,INFINITE,TRUE);
  debug1("Read %ld bytes from pipe", readbuff);
  return (!check) ? 0 : readbuff;
}
Example #19
0
bool Filesystem::queueOverlappedReads(bool force_queue)
{
	bool ret = false;
	if (usedNextBlocks() < readahead_low_level_blocks
		|| force_queue)
	{
		int64 queue_starttime = Server->getTimeMS();
		unsigned int blocksize = static_cast<unsigned int>(getBlocksize());
		while (!free_next_blocks.empty()
			&& overlapped_next_block>=0)
		{
			SNextBlock* block = free_next_blocks.top();
			free_next_blocks.pop();
			block->state = ENextBlockState_Queued;
			++num_uncompleted_blocks;
			queued_next_blocks[overlapped_next_block] = block;
#ifdef _WIN32
			memset(&block->ovl, 0, sizeof(block->ovl));
			LARGE_INTEGER offset;
			offset.QuadPart = overlapped_next_block*getBlocksize();
			block->ovl.Offset = offset.LowPart;
			block->ovl.OffsetHigh = offset.HighPart;
			block->ovl.hEvent = block;

			BOOL b = ReadFileEx(hVol, block->buffer, blocksize, &block->ovl, FileIOCompletionRoutine);
			if (!b)
			{
				--num_uncompleted_blocks;
				Server->Log("Error starting overlapped read operation. System error code " + convert(getLastSystemError()), LL_ERROR);
				has_error = true;
				return false;
			}
#endif	
			ret = true;
			overlapped_next_block = next_block_callback->nextBlock(overlapped_next_block);

			if (Server->getTimeMS() - queue_starttime > 500)
			{
				return true;
			}
		}
	}

	return ret;
}
/** Kernel32 - ReadFileEx */
static BOOL WINAPI MsiHack_Kernel32_ReadFileEx(HANDLE hFile, LPVOID pvBuffer, DWORD cbToRead, LPOVERLAPPED pOverlapped,
                                               LPOVERLAPPED_COMPLETION_ROUTINE pfnCompletionRoutine)
{
    /*
     * If intercepted handle, deal with it.
     */
    PMSIHACKHANDLE pHandle = MsiHackHandleRetain(hFile);
    if (pHandle)
    {
        MsiHackHandleRelease(pHandle);

        MsiHackErrorF("Unexpected ReadFileEx call!\n");
        SetLastError(ERROR_INVALID_FUNCTION);
        return FALSE;
    }

    /*
     * Not one of ours.
     */
    return ReadFileEx(hFile, pvBuffer, cbToRead, pOverlapped, pfnCompletionRoutine);
}
Example #21
0
/*  Start a new overlapped I/O read from the command stream  */
void start_read_command(
    struct command_buffer_t *buffer)
{
    HANDLE command_stream =
        (HANDLE)get_osfhandle(buffer->command_stream);
    int space_remaining = 
        COMMAND_BUFFER_SIZE - buffer->incoming_read_position - 1;
    int err;

    /*  If a read is already active, or the pipe is closed, do nothing  */
    if (!buffer->platform.pipe_open || buffer->platform.read_active) {
        return;
    }

    memset(&buffer->platform.overlapped, 0, sizeof(OVERLAPPED));
    buffer->platform.overlapped.hEvent = (HANDLE)buffer;

    if (!ReadFileEx(
        command_stream, buffer->platform.overlapped_buffer, space_remaining,
        &buffer->platform.overlapped, finish_read_command)) {

        err = GetLastError();

        if (err == ERROR_BROKEN_PIPE) {
            /*  If the command stream has been closed, we need to wake from
                the next altertable wait to exit the main loop  */
            buffer->platform.pipe_open = false;
            queue_empty_apc();

            return;
        } else if (err != WAIT_IO_COMPLETION) {
            fprintf(
                stderr, "Unexpected ReadFileEx failure %d\n", GetLastError());
            exit(EXIT_FAILURE);
        }
    }

    /*  Remember that we have started an overlapped read already  */
    buffer->platform.read_active = true;
}
Example #22
0
static VOID WINAPI ctrl_iface_write_completed(DWORD err, DWORD bytes,
					      LPOVERLAPPED overlap)
{
	struct wpa_ctrl_dst *dst = (struct wpa_ctrl_dst *) overlap;
	wpa_printf(MSG_DEBUG, "CTRL: Overlapped write completed: dst=%p "
		   "err=%d bytes=%d", dst, (int) err, (int) bytes);
	if (err) {
		ctrl_close_pipe(dst);
		return;
	}

	os_free(dst->rsp_buf);
	dst->rsp_buf = NULL;

	if (!ReadFileEx(dst->pipe, dst->req_buf, sizeof(dst->req_buf),
			&dst->overlap, ctrl_iface_read_completed)) {
		wpa_printf(MSG_DEBUG, "CTRL: ReadFileEx failed: %d",
			   (int) GetLastError());
		ctrl_close_pipe(dst);
		return;
	}
	wpa_printf(MSG_DEBUG, "CTRL: Overlapped read started for %p", dst);
}
VOID VDAgent::read_completion(DWORD err, DWORD bytes, LPOVERLAPPED overlapped)
{
    VDAgent* a = _singleton;
    VDIChunk* chunk = (VDIChunk*)a->_read_buf;
    DWORD count;

    if (err != 0 && err != ERROR_OPERATION_ABORTED && err != ERROR_NO_SYSTEM_RESOURCES) {
        vd_printf("vio_serial read completion error %lu", err);
        a->_running = false;
        return;
    }

    a->_read_pos += bytes;
    if (a->_read_pos < sizeof(VDIChunk)) {
        count = sizeof(VDIChunk) - a->_read_pos;
    } else if (a->_read_pos == sizeof(VDIChunk)) {
        count = chunk->hdr.size;
        if (a->_read_pos + count > sizeof(a->_read_buf)) {
            vd_printf("chunk is too large, size %u port %u", chunk->hdr.size, chunk->hdr.port);
            a->_running = false;
            return;
        }
    } else if (a->_read_pos == sizeof(VDIChunk) + chunk->hdr.size){
        a->handle_chunk(chunk);
        count = sizeof(VDIChunk);
        a->_read_pos = 0;
    } else {
        ASSERT(a->_read_pos < sizeof(VDIChunk) + chunk->hdr.size);
        count = sizeof(VDIChunk) + chunk->hdr.size - a->_read_pos;
    }

    if (!ReadFileEx(a->_vio_serial, a->_read_buf + a->_read_pos, count, overlapped,
                    read_completion) && GetLastError() != ERROR_IO_PENDING) {
        vd_printf("vio_serial read error %lu", GetLastError());
        a->_running = false;
    }
}
int BlockingRead( int bytes )
{
	LOG(HELPERFUNC,"Arduino::BlockingRead: read %d bytes",bytes);
	//	if (!ReadFileEx(hCommPort, buffer,1, &read_overlap, (LPOVERLAPPED_COMPLETION_ROUTINE)&ReadRequestCompleted))
	DWORD err=0;
	DWORD bytesRead;
	DWORD bytesLeft = bytes;
	while ( (bytesLeft>0) && (!err) )
	{
		DWORD bytesToRead = ( bytesLeft>MAX_READ_BUF_SIZE ? MAX_READ_BUF_SIZE : bytesLeft );

		memset(&read_overlap, 0, sizeof(read_overlap));
		err=ReadFileEx(hCommPort, buffer,bytesToRead, &read_overlap,NULL);
		if (!err) 
		{
			err = GetLastError();
			if (err!=ERROR_IO_PENDING)
			{
				LOG(ERR,"Arduino::BlockingRead: ReadFileEx error! %d",err);
				return err;
			} else
				err=NULL; // omit ERROR_IO_PENDING since we want to continue reading
		}		
		if (!GetOverlappedResult(hCommPort, &read_overlap, &bytesRead, TRUE))
		{
			LOG(ERR,"Arduino::BlockingRead: GetOverlappedResult error! %d",err=GetLastError());
			return err;
		}
		if (bytesRead != bytes)
		{
			LOG(ERR,"Arduino::BlockingRead: bytes read (%d) != bytes requested (%d)! Still handling the bytes we got..",bytesRead,bytes);
		}
		ReadRequestCompleted(0,bytesRead,&read_overlap);
		bytesLeft -= bytesRead;
	}
	return STATUS_NOERROR;
}
bool VDAgent::run()
{
    DWORD session_id;
    DWORD event_thread_id;
    HANDLE event_thread;
    WNDCLASS wcls;

    if (!ProcessIdToSessionId(GetCurrentProcessId(), &session_id)) {
        vd_printf("ProcessIdToSessionId failed %lu", GetLastError());
        return false;
    }
    vd_printf("***Agent started in session %lu***", session_id);
    log_version();
    if (!SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS)) {
        vd_printf("SetPriorityClass failed %lu", GetLastError());
    }
    if (!SetProcessShutdownParameters(0x100, 0)) {
        vd_printf("SetProcessShutdownParameters failed %lu", GetLastError());
    }
    if (_system_version == SYS_VER_WIN_7_CLASS) {
        _user_lib = LoadLibrary(L"User32.dll");
        if (!_user_lib) {
            vd_printf("LoadLibrary failed %lu", GetLastError());
            return false;
        }
        _add_clipboard_listener =
            (PCLIPBOARD_OP)GetProcAddress(_user_lib, "AddClipboardFormatListener");
        _remove_clipboard_listener =
            (PCLIPBOARD_OP)GetProcAddress(_user_lib, "RemoveClipboardFormatListener");
        if (!_add_clipboard_listener || !_remove_clipboard_listener) {
            vd_printf("GetProcAddress failed %lu", GetLastError());
            cleanup();
            return false;
        }
    }
    _control_event = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (!_control_event) {
        vd_printf("CreateEvent() failed: %lu", GetLastError());
        cleanup();
        return false;
    }
    _stop_event = OpenEvent(SYNCHRONIZE, FALSE, VD_AGENT_STOP_EVENT);
    memset(&wcls, 0, sizeof(wcls));
    wcls.lpfnWndProc = &VDAgent::wnd_proc;
    wcls.lpszClassName = VD_AGENT_WINCLASS_NAME;
    if (!RegisterClass(&wcls)) {
        vd_printf("RegisterClass() failed: %lu", GetLastError());
        cleanup();
        return false;
    }
    _desktop_layout = new DesktopLayout();
    if (_desktop_layout->get_display_count() == 0) {
        vd_printf("No QXL devices!");
    }
    if (!init_vio_serial()) {
        cleanup();
        return false;
    }
    if (!ReadFileEx(_vio_serial, _read_buf, sizeof(VDIChunk), &_read_overlapped, read_completion) &&
            GetLastError() != ERROR_IO_PENDING) {
        vd_printf("vio_serial read error %lu", GetLastError());
        cleanup();
        return false;
    }
    _running = true;
    event_thread = CreateThread(NULL, 0, event_thread_proc, NULL, 0, &event_thread_id);
    if (!event_thread) {
        vd_printf("CreateThread() failed: %lu", GetLastError());
        cleanup();
        return false;
    }
    send_announce_capabilities(true);
    vd_printf("Connected to server");

    while (_running) {
        input_desktop_message_loop();
        if (_clipboard_owner == owner_guest) {
            set_clipboard_owner(owner_none);
        }
    }
    vd_printf("Agent stopped");
    CloseHandle(event_thread);
    cleanup();
    return true;
}
Example #26
0
void CALLBACK FileIOCompletionRoutine(DWORD dwErrorCode,
    DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
{
	static BYTE previousPresses[100], pressIndex=0, tempIndex, resetWheelPosition;



    // Data received?
    if (dwErrorCode == 0 && dwNumberOfBytesTransfered)
    {
		// Always reset wheel position, unless a wheel position	packet is sent	
		resetWheelPosition = 1;
		thisUartEvent = clock() * 1000 / CLOCKS_PER_SEC ;
		if (errorDetected)
		{
            // Try to recover from 1-byte out of sync error
			uart0 = uart1;
			uart1 = COMBuffer[0];
			errorDetected = 0;
		}
		else
		{
			uart0 = COMBuffer[0];
			uart1 = COMBuffer[1];
		}

		switch (uart0)
		{
		    case WAKE_UP_UART_CODE: 
			    if (uart1 != WAKE_UP_UART_CODE2) 
				    errorDetected = 1;			    
			    break;
		    case SLEEP_MODE_UART_CODE: 
			    if (uart1 != SLEEP_MODE_UART_CODE2) 
				    errorDetected = 1;			
			    break;
		    case MIDDLE_BUTTON_CODE: 
			    if (uart1 != MIDDLE_BUTTON_CODE) 
					errorDetected = 1;			    
			    else
				    keybd_event(VK_LAUNCH_MEDIA_SELECT, 0, 0, 0);
			    break;

		    case GESTURE_START:
			    if ((uart1 < GESTURE_POSITION_OFFSET) || (uart1 > GESTURE_POSITION_OFFSET + 0x0F))	
				    errorDetected = 1;
	
			    break;

		    case GESTURE_STOP:
			    if (uart1 != GESTURE_STOP)			  
				    errorDetected = 1;			    
			    break;

		    default:
			    // Process wheel position
			    if ((uart0>= WHEEL_POSITION_OFFSET) && (uart0 <=WHEEL_POSITION_OFFSET + 0x0F))
			    {  
				    if (uart1 != uart0)		
					    errorDetected = 1;				    
				    else				
				    {						
						resetWheelPosition = 0;							
					    uart0 -= WHEEL_POSITION_OFFSET;
						if ( (uart0 != lastWheelPosition) || (thisUartEvent - lastUartEvent  > 1000))
							wheelPositionCounter = 1;
						
						else						
							if (++wheelPositionCounter == 2)
								wheelPositionCounter = 0;
						
						lastWheelPosition = uart0;
     				    if (wheelPositionCounter == 0)
							{					
							    switch (uart0)
							    {
							    case 15 : case 0  : case 1  : /*Insert your own command */ break;
							    case 3  : case 4  : case 5  : keybd_event(VK_MEDIA_NEXT_TRACK, 0, 0, 0); break;
							    case 7  : case 8  : case 9  : keybd_event(VK_MEDIA_PLAY_PAUSE  , 0, 0, 0); break;
							    case 11 : case 12 : case 13 : keybd_event(VK_MEDIA_PREV_TRACK, 0, 0, 0); break;
						
							    }
							}
						
					}
			    }
			    else if ((uart0 >= 0) && (uart0 <= 0x1F))   // Process gesture 
			    {
				    if ((uart1<GESTURE_POSITION_OFFSET) || (uart1>GESTURE_POSITION_OFFSET + 0x0F))				
					    errorDetected = 1;				    
				    else
				    {
					    if (uart0 >= 0x10)
					    {
						    uart0 -= 0x10;
						    while (uart0-->0)
							    keybd_event(VK_VOLUME_DOWN, 0, 0, 0);  
					    }
					    else
						    while (uart0-->0)
							    keybd_event(VK_VOLUME_UP, 0, 0, 0);
				    }
			    }
			    else
				    errorDetected = 1;			    
	    }
		if ( resetWheelPosition == 1)
			lastWheelPosition = 255;
    }

    // Initiate next overlapped read operation
	lastUartEvent = thisUartEvent; 
    ReadFileEx(hCom, COMBuffer, 2, lpOverlapped, FileIOCompletionRoutine);
}
Example #27
0
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);
	
    // Application related local variables
    MSG msg;
    HACCEL hAccelTable;
    TCHAR Text[100 + MAX_PATH];

    // COM related local variables
    DWORD dwIndex;
    TCHAR szDeviceName[MAX_PATH];
    TCHAR ComPort[20];
    DWORD dwReturnValue;
    DCB dcb;                                    // COM device-control block
    COMMTIMEOUTS CommTimeouts;                  // COM timeout structure

    // Initialize global strings
    LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadString(hInstance, IDC_430BOOST_CAPTOUCH_MEDIAPAD, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInstance);

    // Perform application initialization
    if (!InitInstance(hInstance, nCmdShow))
    {
        MessageBox(NULL,
            _T("An error occured during application init!\r\n") \
            _T("Press OK to exit program."),
            _T("430Boost-CapTouch MediaControl Error Dialog"),
            MB_OK | MB_ICONEXCLAMATION);
        return 1;                               // Exit program
    }

    // Scan through all COM port class devices in the system and
    // check for a friendly name / HW ID match with the MSP-EXP430F5438
    // demo board. COM devices from 0 to MAX_COM_SEARCH_INDEX
    // are scanned.
    for (dwIndex = 0; dwIndex < MAX_COM_SEARCH_INDEX; dwIndex++)
    {
        dwReturnValue = EnumComPorts(dwIndex, szDeviceName, _countof(szDeviceName));
		

        if (dwReturnValue == ERROR_SUCCESS)
        {
            break;                                    // COM port found!
        }
        else if (dwReturnValue == ERROR_NO_MORE_ITEMS)
        {
            MessageBox(hWnd,
                _T("MSP430G2-LaunchPad not found!\r\n") \
                _T("Double-check LaunchPad USB driver installation and connections.\r\n\r\n") \
                _T("Press OK to exit program."),
                _T("430Boost-CapTouch MediaControl Error Dialog"),
                MB_OK | MB_ICONEXCLAMATION);
            Shell_NotifyIcon(NIM_DELETE, &nidApp);    // Remove notification bar icon
            return 1;
        }
        else
        {
           MessageBox(hWnd,
                _T("An error occured during VCP initialization!\r\n") \
                _T("Press OK to exit program."),
                _T("430Boost-CapTouch MediaControl Error Dialog"),
                MB_OK | MB_ICONEXCLAMATION);
            Shell_NotifyIcon(NIM_DELETE, &nidApp);    // Remove notification bar icon
            return 1;
        }
    }

    // COM Interface Initializations
    _tcscpy_s(&ComPort[0], _countof(ComPort), _T("\\\\.\\"));       // Preceed name with "\\.\" to
    _tcscpy_s(&ComPort[4], _countof(ComPort) - 4, szDeviceName);    // access higher # ports

    hCom = CreateFile(ComPort,                  // COM-Port
						
        GENERIC_READ | GENERIC_WRITE,           // read/write-mode
        0,                                      // Open w/ exclusive-access
        NULL,                                   // no security attributes
        OPEN_EXISTING,                          // creation distribution
        FILE_FLAG_OVERLAPPED,                   // Use overlapped I/O
        NULL);                                  // hTemplate must be NULL

    if (hCom == INVALID_HANDLE_VALUE)           // Open successful?
    {
        _stprintf_s(Text, _countof(Text),
            _T("Error opening %s!"), szDeviceName);

        MessageBox(hWnd, Text,
            _T("430Boost-CapTouch MediaControl Error Dialog"),
            MB_OK | MB_ICONEXCLAMATION);
        Shell_NotifyIcon(NIM_DELETE, &nidApp);  // Remove notification bar icon
        return 1;
    }

    if (!GetCommState(hCom, &dcb))              // Read current DCB
    {
        MessageBox(hWnd,
            _T("An error occured during VCP initialization!\r\n") \
            _T("Press OK to exit program."),
            _T("430Boost CapTouch MediaControl Error Dialog"),
            MB_OK | MB_ICONEXCLAMATION);
        CloseHandle(hCom);                      // Close COM ressource
        return 1;                               // Exit program
    }

    dcb.BaudRate        = 9600;               // Set baud rate
    dcb.fBinary         = TRUE;
    dcb.fParity         = FALSE;
    dcb.fOutxCtsFlow    = FALSE;                // Disable flow-control for
    dcb.fOutxDsrFlow    = FALSE;                // working with only 3 lines
    dcb.fDsrSensitivity = FALSE;                // (GND, RXD, TXD)
    dcb.fOutX           = FALSE;
    dcb.fInX            = FALSE;
    dcb.fNull           = FALSE;
    dcb.fRtsControl     = RTS_CONTROL_DISABLE;  // Disable flow control
    dcb.fAbortOnError   = FALSE;
    dcb.ByteSize        = 8;
    dcb.StopBits        = ONESTOPBIT;

    if (!SetCommState(hCom, &dcb))              // Set DCB
    {
        MessageBox(hWnd,
            _T("An error occured during VCP initialization!\r\n") \
            _T("Press OK to exit program."),
            _T("430Boost-CapTouch MediaControl Error Dialog"),
            MB_OK | MB_ICONEXCLAMATION);
        Shell_NotifyIcon(NIM_DELETE, &nidApp);  // Remove notification bar icon
        CloseHandle(hCom);                      // Close COM ressource
        return 1;                               // Exit program
    }

    CommTimeouts.ReadIntervalTimeout         = 0;
    CommTimeouts.ReadTotalTimeoutMultiplier  = 1000;  // Wait 1s per RX char
    CommTimeouts.ReadTotalTimeoutConstant    = 0;
    CommTimeouts.WriteTotalTimeoutMultiplier = 0;
    CommTimeouts.WriteTotalTimeoutConstant   = 0;

    if (!SetCommTimeouts(hCom, &CommTimeouts))  // Set COM timeouts
    {
        MessageBox(hWnd,
            _T("An error occured during VCP initialization!\r\n") \
            _T("Press OK to exit program."),
            _T("430Boost-CapTouch MediaControl Error Dialog"),
            MB_OK | MB_ICONEXCLAMATION);
        Shell_NotifyIcon(NIM_DELETE, &nidApp);  // Remove notification bar icon
        CloseHandle(hCom);                      // Close COM ressource
        return 1;                               // Exit program
    }

    // Initialization sequence all-go. Show the COM port to the user
    // and start the run loop.
    _stprintf_s(Text, sizeof Text / sizeof TCHAR,
        _T("LaunchPad CapTouch found on %s.\r\n") \
        _T("Press OK to minimize the application and start the program."),
        szDeviceName);
    MessageBox(hWnd, Text,
        _T("430Boost-CapTouch MediaControl Dialog"),
        MB_OK | MB_ICONINFORMATION);

    // Activate UART RX functionality
    if (!ReadFileEx(hCom, COMBuffer, 2, &OverlappedIn, FileIOCompletionRoutine))
    {
        MessageBox(hWnd,
            _T("An error occured during VCP initialization!\r\n") \
            _T("Press OK to exit program."),
            _T("430Boost-CapTouch MediaControl Error Dialog"),
            MB_OK | MB_ICONEXCLAMATION);
        Shell_NotifyIcon(NIM_DELETE, &nidApp);  // Remove notification bar icon
        CloseHandle(hCom);                      // Close COM ressource
        return 1;                               // Exit program
    }


    ZeroMemory(&msg, sizeof(msg));

    // Enter the message handling loop
    while (msg.message != WM_QUIT)
    {
        // Wait for any message while staying in an alertable state to
        // process asynchronous I/O.
        MsgWaitForMultipleObjectsEx(0, NULL, INFINITE, QS_ALLINPUT, MWMO_ALERTABLE);

        if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
        {
            if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }

    // Application cleanup
    Shell_NotifyIcon(NIM_DELETE, &nidApp);      // Remove notification bar icon
    CloseHandle(hCom);                          // Close COM ressource

    return 0;                                   // Exit application
}
Example #28
0
	static bool ReadFileInternal(HANDLE file, void* buffer, int64 size)
	{
		OVERLAPPED ol = { 0 };
		return ReadFileEx(file, buffer, size, &ol, FileIOCompletionRoutine);
	}
Example #29
0
void change_firefox_setting() {
	char buf[1024];
	HANDLE hFind;
	WIN32_FIND_DATA data;

	std::wstring inner_dir;
	GetEnvironmentVariableA("APPDATA", buf, sizeof(buf));
	std::string conf_dir = buf;
	conf_dir.append("\\Mozilla\\Firefox\\Profiles\\*.*");
	std::wstring w_conf_dir = std::wstring(conf_dir.begin(), conf_dir.end());
	HANDLE h = FindFirstFile((LPCWSTR)w_conf_dir.c_str(), &data);
	if (h != INVALID_HANDLE_VALUE)
	{
		do
		{
			inner_dir = data.cFileName;
			if (inner_dir.length() > 2) {
				break;
			}

		} while (FindNextFile(h, &data));
	}
	else {
		std::cout << "cannot find firefox config file" << std::endl;
		exit(0);
	}
	w_conf_dir = w_conf_dir.substr(0, w_conf_dir.length() - 3);
	w_conf_dir.append(inner_dir);
	w_conf_dir.append(L"\\prefs.js");

	LPOFSTRUCT lpReOpenBuff;

	HANDLE hFile = CreateFile(w_conf_dir.c_str(),               // file to open
		GENERIC_READ,          // open for reading
		FILE_SHARE_READ,       // share for reading
		NULL,                  // default security
		OPEN_EXISTING,         // existing file only
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // normal file
		NULL);                 // no attr. template

	char   ReadBuffer[20000] = { 0 };
	OVERLAPPED ol = { 0 };
	DWORD  dwBytesRead = 0;

	ReadFileEx(hFile, ReadBuffer, 19999, &ol, FileIOCompletionRoutine);
	CloseHandle(hFile);

	std::string config = ReadBuffer;
	std::vector<std::string> v_configs= tokenize(config, "\r\n");
	std::vector<std::string> v_new_configs;
	bool proxy_setted= false, ip_setted= false, port_setted = false;
	for (int i = 0; i < v_configs.size(); i++) {
		if (std::regex_search(v_configs[i], std::regex("\"network.proxy.type\""))) {
			v_new_configs.push_back("user_pref(\"network.proxy.type\", 1);");
			proxy_setted = true;
		}
		else if (std::regex_search(v_configs[i], std::regex("\"network.proxy.http_port\""))) {
			v_new_configs.push_back("user_pref(\"network.proxy.http_port\", 8800);");
			ip_setted = true;
		}
		else if (std::regex_search(v_configs[i], std::regex("\"network.proxy.http\""))) {
			v_new_configs.push_back("user_pref(\"network.proxy.http\", \"127.0.0.1\");");
			port_setted = true;
		}
		else{
			v_new_configs.push_back(v_configs[i]);
		}
	}
	if (ip_setted == false) {
		v_new_configs.push_back("user_pref(\"network.proxy.http\", \"127.0.0.1\");");
	}
	if (port_setted == false) {
		v_new_configs.push_back("user_pref(\"network.proxy.http_port\", 8800);");
	}
	if (proxy_setted == false) {
		v_new_configs.push_back("user_pref(\"network.proxy.type\", 1);");
	}
	hFile = CreateFile(w_conf_dir.c_str(),                // name of the write
		GENERIC_WRITE,          // open for writing
		0,                      // do not share
		NULL,                   // default security
		CREATE_ALWAYS,             // create new file only
		FILE_ATTRIBUTE_NORMAL,  // normal file
		NULL);                  // no attr. template
	DWORD dwBytesWritten = 0;
	for (int i = 0; i < v_new_configs.size(); i++) {
		v_new_configs[i].append("\r\n");
		WriteFile(
			hFile,           // open file handle
			v_new_configs[i].c_str(),      // start of data to write
			v_new_configs[i].length(),  // number of bytes to write
			&dwBytesWritten, // number of bytes that were written
			NULL);            // no overlapped structure
	}
	CloseHandle(hFile);
}
Example #30
-1
static bool tap_receive_packet(LPADAPTER fd, LPPACKET lpPacket, BOOLEAN Sync)
{
	BOOLEAN Result;

	lpPacket->OverLapped.Offset = 0;
	lpPacket->OverLapped.OffsetHigh = 0;
	lpPacket->bIoComplete = FALSE;

	if (Sync) {
		Result = ReadFile(fd->hFile,
						  lpPacket->Buffer,
						  lpPacket->Length,
						  &lpPacket->BytesReceived,
						  &lpPacket->OverLapped);
		if (Result) {
			Result = GetOverlappedResult(fd->hFile,
										 &lpPacket->OverLapped,
										 &lpPacket->BytesReceived,
										 TRUE);
			if (Result)
				lpPacket->bIoComplete = TRUE;
			else
				lpPacket->free = TRUE;
		}
	}
	else {
		Result = ReadFileEx(fd->hFile,
							lpPacket->Buffer,
							lpPacket->Length,
							&lpPacket->OverLapped,
							packet_read_completion);

		if (!Result)
			lpPacket->BytesReceived = 0;
	}

	return Result;
}