Пример #1
0
int remote_thumbnail::connect(const wchar_t *pipename)
{
	disconnect();
	while (1)
	{
		m_pipe = CreateFile(pipename,   // pipe name 
			GENERIC_READ | GENERIC_WRITE, 
			0,              // no sharing 
			NULL,           // default security attributes
			OPEN_EXISTING,  // opens existing pipe 
			0,              // default attributes 
			NULL);          // no template file 

		// Break if the pipe handle is valid. 
		if (m_pipe != INVALID_HANDLE_VALUE) 
			return connect(m_pipe);

		// Exit if an error other than ERROR_PIPE_BUSY occurs.
		if (GetLastError() != ERROR_PIPE_BUSY)
			return error_connect_error;

		// All pipe instances are busy, so wait for 2 seconds.
		if ( ! WaitNamedPipe(pipename, 2000)) 
			return error_connect_timeout;
	}

	return error_connect_error;
}
Пример #2
0
/* Return: amount of PDU data */
uint16_t MSTP_Get_Send(
    volatile struct mstp_port_struct_t * mstp_port,
    unsigned timeout)
{       /* milliseconds to wait for a packet */
    (void) mstp_port;
    (void) timeout;
    return 0;
}

uint16_t MSTP_Get_Reply(
    volatile struct mstp_port_struct_t * mstp_port,
    unsigned timeout)
{       /* milliseconds to wait for a packet */
    (void) mstp_port;
    (void) timeout;
    return 0;
}

static char Capture_Filename[32] = "mstp_20090123091200.cap";
static FILE *pFile = NULL;      /* stream pointer */
#if defined(_WIN32)
static HANDLE hPipe = INVALID_HANDLE_VALUE;     /* pipe handle */
static void named_pipe_create(
    char *pipe_name)
{
    fprintf(stdout, "mstpcap: Creating Named Pipe \"%s\"\n", pipe_name);
    /* create the pipe */
    while (hPipe == INVALID_HANDLE_VALUE)
    {
        /* use CreateFile rather than CreateNamedPipe */
        hPipe = CreateFile(
            pipe_name,
            GENERIC_READ |
            GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            0,
            NULL);
        if (hPipe != INVALID_HANDLE_VALUE) {
            break;
        }
        /* if an error occured at handle creation */
        if (!WaitNamedPipe(pipe_name, 20000)) {
            printf("Could not open pipe: waited for 20sec!\n"
                "If this message was issued before the 20sec finished,\n"
                "then the pipe doesn't exist!\n");
            Exit_Requested = true;
            return;
        }
    }
    ConnectNamedPipe(hPipe, NULL);
}
Пример #3
0
//----------------------------------------------------------------------
// connect
//----------------------------------------------------------------------
bool NamedPipeConnection::connect()
{
    LBASSERT( getDescription()->type == CONNECTIONTYPE_NAMEDPIPE );

    if( !isClosed( ))
        return false;

    _setState( STATE_CONNECTING );

    const std::string filename = _getFilename();
    if ( !WaitNamedPipe( filename.c_str(), 20000 ))
    {
        LBERROR << "Can't create named pipe: " << lunchbox::sysError << std::endl;
        return false;
    }

    if( !_connectNamedPipe( ))
        return false;

    _initAIORead();
    _setState( STATE_CONNECTED );

    LBINFO << "Connected " << getDescription()->toString() << std::endl;
    return true;
}
Пример #4
0
/*	OpenDatabase - open pipe to database
 *
 *	returns HANDLE to database pipe
 */
HANDLE OpenDatabase (BOOL fNoise)
{
    HANDLE h;

    while (TRUE) {
	h = CreateFile (szServerPipe,
			(GENERIC_READ | GENERIC_WRITE),
			(FILE_SHARE_READ | FILE_SHARE_WRITE),
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			NULL);

	if (h != (HANDLE)-1)
	    break;

	if (GetLastError () != ERROR_PIPE_BUSY) {
	    printf ("OpenDatabase(%s) returned %x\n", szServerPipe, GetLastError ());
	    break;
	    }
	if (fNoise)
	    printf (".");
	WaitNamedPipe (szServerPipe,  NMPWAIT_USE_DEFAULT_WAIT);
	}

    return h;
}
Пример #5
0
/**
*	Liga ao servidor.
*	Retorna 1,
*	caso contrário, código associado ao erro.
*/
int InicializarPipes(HANDLE * hPipe, HANDLE * hPipeJogo, TCHAR * ipServ) {
	TCHAR pipeName[BUFFERSIZE] = TEXT("\\\\");
	TCHAR pipeNameJogo[BUFFERSIZE] = TEXT("\\\\");
	if (ipServ == NULL) {
		_tcscat(pipeName, TEXT("."));
		_tcscpy(pipeName, TEXT("."));
	}
	else {
		_tcscat(pipeName, ipServ);
		_tcscat(pipeNameJogo, ipServ);
	}
	_tcscat(pipeName, PIPE_NAME_SUFFIX);
	_tcscat(pipeNameJogo, PIPE_NAME_JOGO_SUFFIX);

	if (!WaitNamedPipe(pipeName, NMPWAIT_WAIT_FOREVER)) {
		return 0;
	}
	if ((*hPipe = CreateFile(pipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == NULL) {
		return -1;
	}
	if ((*hPipeJogo = CreateFile(pipeNameJogo, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == NULL) {
		return -2;
	}
	return 1;
}
Пример #6
0
bool Watcher::install()
{
	//return(true);


	DWORD rd;
	char msg[MAX_PATH + 2];
	std::string current;

	Base *b = Base::instance();
	if (b->isInstalled())
		return(true);
	if (!b->install())
		return(false);

	DisconnectNamedPipe(pipe);
	CloseHandle(pipe);
	pipe = NULL;

	*(WORD *)msg = 1;
	b->getCurrentPath(current);
	strcpy(msg + 2, current.c_str());
	Sleep(10000);
	//MessageBoxA(NULL, msg + 2, "send dcmd", MB_OK);
	WaitNamedPipe(pipename.c_str(), 10000);
	CallNamedPipe(pipename.c_str(), msg, sizeof(msg), NULL, 0, &rd, 0);
	terminate();
	return(true);
}
Пример #7
0
HRESULT NamedPipeChannel::Open(const base::StringPiece16& name, DWORD timeout) {
  base::AutoLock guard(lock_);

  if (work_ == nullptr || handle_ != INVALID_HANDLE_VALUE || io_ != nullptr)
    return E_HANDLE;

  auto pipe_name = kPipeNamePrefix + name.as_string();

  if (!WaitNamedPipe(pipe_name.c_str(), timeout))
    return HRESULT_FROM_WIN32(GetLastError());

  handle_ = CreateFile(pipe_name.c_str(), GENERIC_READ | GENERIC_WRITE,
                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                       nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
  if (handle_ == INVALID_HANDLE_VALUE)
    return HRESULT_FROM_WIN32(GetLastError());

  io_ = CreateThreadpoolIo(handle_, OnCompleted, this, nullptr);
  if (io_ == nullptr)
    return HRESULT_FROM_WIN32(GetLastError());

  end_point_ = EndPoint::kClient;

  return S_OK;
}
Пример #8
0
HRESULT NamedPipe::ConnectTo(const wchar_t* name, DWORD timeout) {
  base::AutoLock guard(lock_);

  if (work_ == nullptr || pipe_ != INVALID_HANDLE_VALUE || io_ != nullptr)
    return E_HANDLE;

  if (name == nullptr)
    return E_INVALIDARG;

  wchar_t pipe_name[256];
  swprintf_s(pipe_name, L"\\\\.\\pipe\\%s", name);

  if (!WaitNamedPipe(pipe_name, timeout))
    return HRESULT_FROM_WIN32(GetLastError());

  pipe_ = CreateFile(pipe_name, GENERIC_READ | GENERIC_WRITE,
                     FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
                     FILE_FLAG_OVERLAPPED, NULL);
  if (pipe_ == INVALID_HANDLE_VALUE)
    return HRESULT_FROM_WIN32(GetLastError());

  io_ = CreateThreadpoolIo(pipe_, OnCompleted, this, nullptr);
  if (io_ == nullptr)
    return HRESULT_FROM_WIN32(GetLastError());

  return S_OK;
}
HANDLE admin_connect(void)
{
    HANDLE hMsgPipe = INVALID_HANDLE_VALUE;

    // Name of the pipe the admin client creates
    const int MAX_PIPE_BUF_SIZE = 1024;
    char pipeName[MAX_PIPE_BUF_SIZE];
    sprintf(pipeName, "\\\\.\\pipe\\iWSAdmin-%s", unique_name);

    for (;;) {
        // Attempt to connect to the admin client
        hMsgPipe = CreateFile(pipeName, GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
                              0, NULL);
        if (hMsgPipe != INVALID_HANDLE_VALUE)
            break;
        if (GetLastError() != ERROR_PIPE_BUSY)
            break;

        // Wait 20 seconds to establish a connection
        if (!WaitNamedPipe(pipeName, 20000))
            break;
    }

    if (hMsgPipe != INVALID_HANDLE_VALUE) {
        DWORD dwMode = PIPE_READMODE_MESSAGE;
        BOOL fSuccess = SetNamedPipeHandleState(hMsgPipe, &dwMode, NULL, NULL);
        if (!fSuccess) {
            CloseHandle(hMsgPipe);
            hMsgPipe = INVALID_HANDLE_VALUE;
        }
    }

    return hMsgPipe;
}
Пример #10
0
int main(int argc, char* argv[]) {
  static wchar_t pipe_name[BUFFER_SIZE];
  int i = 0;
  int exit_code = 0;
  const wchar_t* clcache_dir = NULL;

  clcache_dir = get_env_variable(L"CLCACHE_DIR");
  if (clcache_dir[0] == 0) {
    fprintf(stderr, "Failed get CLCACHE_DIR environment variable.\n");
    return 1;
  }
  if (!generate_pipe_name(pipe_name, clcache_dir)) {
    fprintf(stderr,"CLCACHE_DIR Too large.\n");
    return 1;
  }
  while(1) {
    if (try_do_work(pipe_name, &exit_code)) {
      return exit_code;
    }
    if (!WaitNamedPipe(pipe_name, NMPWAIT_WAIT_FOREVER)) {
      fprintf(stderr,"Failed wait for named pipe. Error %d\n", GetLastError());
      return -1;
    }
  }
  return 0;
}
Пример #11
0
CCircuitry* CNeighbour::ConnectTo(LPCTSTR xUserId, DWORD nTimeOut)
{
	CSingleLock pLock( &m_pSection, TRUE );
	
	CCircuitry* pChannel = FindChannel( xUserId );
	if ( pChannel ) return pChannel;
	
	NETRESOURCE ns;
	
	ns.dwScope = RESOURCE_CONNECTED;   
	ns.dwType = RESOURCETYPE_ANY; 
	ns.dwDisplayType = RESOURCEDISPLAYTYPE_GENERIC;
	ns.dwUsage = RESOURCEUSAGE_CONNECTABLE;
	
	ns.lpRemoteName	= Settings.Centric.Remote.GetBuffer(0);
	ns.lpLocalName = NULL;
	ns.lpProvider = NULL;
	
	WNetAddConnection2( &ns, Settings.Centric.Password, Settings.Centric.UserId, 0 );
	
	if ( ! WaitNamedPipe( Settings.Centric.Remote, nTimeOut ) ) return NULL;
	
	pChannel = SetChannel( new CCircuitry( xUserId ) );
	pChannel->ConnectTo( Settings.Centric.Remote, nTimeOut  );
	
	pChannel->SendPacket( new CBindPacket( xUserId, "" ) );
	
	Connect(); return pChannel;
}
Пример #12
0
bool CRemoteCacheLink::EnsureCommandPipeOpen()
{
	AutoLocker lock(m_critSec);
	if(m_hCommandPipe != INVALID_HANDLE_VALUE)
	{
		return true;
	}

	m_hCommandPipe = CreateFile(
		GetCacheCommandPipeName(),		// pipe name
		GENERIC_READ |					// read and write access
		GENERIC_WRITE,
		0,								// no sharing
		NULL,							// default security attributes
		OPEN_EXISTING,					// opens existing pipe
		FILE_FLAG_OVERLAPPED,			// default attributes
		NULL);							// no template file

	if (m_hCommandPipe == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PIPE_BUSY)
	{
		// TSVNCache is running but is busy connecting a different client.
		// Do not give up immediately but wait for a few milliseconds until
		// the server has created the next pipe instance
		if (WaitNamedPipe(GetCacheCommandPipeName(), 50))
		{
			m_hCommandPipe = CreateFile(
				GetCacheCommandPipeName(),		// pipe name
				GENERIC_READ |					// read and write access
				GENERIC_WRITE,
				0,								// no sharing
				NULL,							// default security attributes
				OPEN_EXISTING,					// opens existing pipe
				FILE_FLAG_OVERLAPPED,			// default attributes
				NULL);							// no template file
		}
	}


	if (m_hCommandPipe != INVALID_HANDLE_VALUE)
	{
		// The pipe connected; change to message-read mode.
		DWORD dwMode;

		dwMode = PIPE_READMODE_MESSAGE;
		if(!SetNamedPipeHandleState(
			m_hCommandPipe,    // pipe handle
			&dwMode,  // new pipe mode
			NULL,     // don't set maximum bytes
			NULL))    // don't set maximum time
		{
			ATLTRACE("SetNamedPipeHandleState failed");
			CloseHandle(m_hCommandPipe);
			m_hCommandPipe = INVALID_HANDLE_VALUE;
			return false;
		}
		return true;
	}

	return false;
}
Пример #13
0
bool QueryData::UpdateByPipe(LPSVDBQUERY lpquery,const char *pdata,S_UINT len,LPSVDBRESULT ret,string addr,S_UINT timeout)
{
#ifdef	WIN32

	DWORD to= (timeout==-1)? NMPWAIT_WAIT_FOREVER : timeout*1000;

	if(WaitNamedPipe(m_pipename,to)==0)
	{
		return false;
	}

	
	HANDLE hand=::CreateFile(m_pipename,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,
		OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
	if(hand!=INVALID_HANDLE_VALUE)
	{
		if(!Pipe_Send(hand,(void *)lpquery,sizeof(SVDBQUERY)))
		{
			::CloseHandle(hand);
			return false;
		}

		if(!Pipe_Send(hand,(void *)pdata,len))
		{
			::CloseHandle(hand);
			return false;
		}

		char *pert=NULL;
		S_UINT rlen=0;
		if(!Pipe_Recev(hand,(void **)&pert,rlen))
		{
			::CloseHandle(hand);
			return false;
		}
		if(rlen!=sizeof(SVDBRESULT))
		{
			::CloseHandle(hand);
			if(pert!=NULL)
				delete [] pert;
			return false;
		}
		memcpy(ret,pert,rlen);
		delete [] pert;

		::CloseHandle(hand);
		return ret->state==SVDB_OK;

	}else
	{
		return false;
	}


#else

#endif
	return true;
}
Пример #14
0
struct wpa_ctrl * wpa_ctrl_open(const char *ctrl_path)
{
	struct wpa_ctrl *ctrl;
	DWORD mode;
	TCHAR name[256];
	int i, ret;

	ctrl = os_malloc(sizeof(*ctrl));
	if (ctrl == NULL)
		return NULL;
	os_memset(ctrl, 0, sizeof(*ctrl));

#ifdef UNICODE
	if (ctrl_path == NULL)
		ret = _snwprintf(name, 256, NAMED_PIPE_PREFIX);
	else
		ret = _snwprintf(name, 256, NAMED_PIPE_PREFIX TEXT("-%S"),
				 ctrl_path);
#else /* UNICODE */
	if (ctrl_path == NULL)
		ret = os_snprintf(name, 256, NAMED_PIPE_PREFIX);
	else
		ret = os_snprintf(name, 256, NAMED_PIPE_PREFIX "-%s",
				  ctrl_path);
#endif /* UNICODE */
	if (os_snprintf_error(256, ret)) {
		os_free(ctrl);
		return NULL;
	}

	for (i = 0; i < 10; i++) {
		ctrl->pipe = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0,
					NULL, OPEN_EXISTING, 0, NULL);
		/*
		 * Current named pipe server side in wpa_supplicant is
		 * re-opening the pipe for new clients only after the previous
		 * one is taken into use. This leaves a small window for race
		 * conditions when two connections are being opened at almost
		 * the same time. Retry if that was the case.
		 */
		if (ctrl->pipe != INVALID_HANDLE_VALUE ||
		    GetLastError() != ERROR_PIPE_BUSY)
			break;
		WaitNamedPipe(name, 1000);
	}
	if (ctrl->pipe == INVALID_HANDLE_VALUE) {
		os_free(ctrl);
		return NULL;
	}

	mode = PIPE_READMODE_MESSAGE;
	if (!SetNamedPipeHandleState(ctrl->pipe, &mode, NULL, NULL)) {
		CloseHandle(ctrl->pipe);
		os_free(ctrl);
		return NULL;
	}

	return ctrl;
}
Пример #15
0
// static
bool Channel::IsNamedServerInitialized(
	const std::string& channel_id) {
	if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
		return true;
	// If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
	// connection.
	return GetLastError() == ERROR_SEM_TIMEOUT;
}
Пример #16
0
bool clNamedPipeClient::connect(long )
{
#ifdef __WXMSW__
	this->setLastError(ZNP_OK);

	while (1) {
		_pipeHandle = CreateFile(
		                  getPipePath(),  // pipe name
		                  GENERIC_READ |  // read and write access
		                  GENERIC_WRITE,
		                  0,              // no sharing
		                  NULL,           // default security attributes
		                  OPEN_EXISTING,  // opens existing pipe
		                  0,              // default attributes
		                  NULL);          // no template file

		if (_pipeHandle != INVALID_PIPE_HANDLE)
			return true;

		// Exit if an error other than ERROR_PIPE_BUSY occurs.
		DWORD err = GetLastError();
		if (err != ERROR_PIPE_BUSY) {
			this->setLastError(ZNP_CONNECT_ERROR);
			return false;
		}

		// All pipe instances are busy, so wait for 20 seconds.

		if (!WaitNamedPipe(getPipePath(), 20000)) {
			DWORD err = GetLastError();
			if (err == WAIT_TIMEOUT) {
				this->setLastError(ZNP_TIMEOUT);
			} else {
				this->setLastError(ZNP_CONNECT_WAIT_ERROR);
			}
			return false;
		}
	}
#else // MSW
	struct sockaddr_un server;
	
	_pipeHandle = socket(AF_UNIX, SOCK_STREAM, 0);
	if (_pipeHandle < 0) {
		perror("ERROR");
		return false;
	}
	
	server.sun_family = AF_UNIX;
	strcpy(server.sun_path, getPipePath());

	if (::connect(_pipeHandle, (struct sockaddr *) &server, sizeof(struct sockaddr_un)) < 0) {
		perror("ERROR");
		disconnect();
		return false;
	}
	return true;
#endif
}
Пример #17
0
BOOL ipcPipeCltChannel::Connect()
{
    BOOL bReturn = FALSE;

    if (m_hPipe)
    {
        bReturn = TRUE;
        goto Exit0;
    }
    
    do
    { 
        m_hPipe = CreateFile( 
            m_strPipeName.c_str(),
            GENERIC_READ | GENERIC_WRITE, 
            0,
            NULL,
            OPEN_EXISTING,
            0,
            NULL);
        if (m_hPipe != INVALID_HANDLE_VALUE) 
            break; 

        DWORD dwError = GetLastError();
        //LOGA("ipcPipeCltChannel::Connect CreateFile error:%d", dwError);
        if (dwError != ERROR_PIPE_BUSY) 
        {
            goto Exit0;
        }

        // All pipe instances are busy, so wait for 1 second. 
        if (!WaitNamedPipe(m_strPipeName.c_str(), 1000)) 
        { 
            goto Exit0;
        }
    } while (true);

    // The pipe connected; change to message-read mode. 
    DWORD dwMode = PIPE_READMODE_BYTE; 
    BOOL bSuccess;
    bSuccess = SetNamedPipeHandleState( 
        m_hPipe,    // pipe handle 
        &dwMode,  // new pipe mode 
        NULL,     // don't set maximum bytes 
        NULL);    // don't set maximum time 
    if (!bSuccess) 
    {
        goto Exit0;
    }

    bReturn = TRUE;
    
Exit0:
    if (!bReturn) m_hPipe = NULL;
    
    return bReturn;
}
Пример #18
0
w_stm_t w_stm_connect_named_pipe(const char *path, int timeoutms) {
  w_stm_t stm = NULL;
  HANDLE handle;
  DWORD err;
  DWORD64 deadline = GetTickCount64() + timeoutms;

  if (strlen(path) > 255) {
    w_log(W_LOG_ERR, "w_stm_connect_named_pipe(%s) path is too long\n", path);
    errno = E2BIG;
    return NULL;
  }

retry_connect:
  handle = CreateFile(path,
      GENERIC_READ|GENERIC_WRITE,
      0,
      NULL,
      OPEN_EXISTING,
      FILE_FLAG_OVERLAPPED,
      NULL);

  if (handle != INVALID_HANDLE_VALUE) {
    stm = w_stm_handleopen(handle);
    if (!stm) {
      CloseHandle(handle);
    }
    return stm;
  }

  err = GetLastError();
  if (timeoutms > 0) {
    timeoutms -= (DWORD)(GetTickCount64() - deadline);
  }
  if (timeoutms <= 0 || (err != ERROR_PIPE_BUSY &&
        err != ERROR_FILE_NOT_FOUND)) {
    // either we're out of time, or retrying won't help with this error
    errno = map_win32_err(err);
    return NULL;
  }

  // We can retry
  if (!WaitNamedPipe(path, timeoutms)) {
    err = GetLastError();
    if (err == ERROR_SEM_TIMEOUT) {
      errno = map_win32_err(err);
      return NULL;
    }
    if (err == ERROR_FILE_NOT_FOUND) {
      // Grace to allow it to be created
      SleepEx(10, true);
    }
  }

  goto retry_connect;
}
Пример #19
0
int Cliente::connect() {
	HANDLE hThread = NULL;
	DWORD  dwThreadId = 0;
	fSuccess = FALSE;

	// Try to open a named pipe; wait for it, if necessary. 
	while (1)
	{
		hPipe = CreateFile(
			lpszPipename,   // pipe name 
			GENERIC_READ |  // read and write access 
			GENERIC_WRITE,
			0,              // no sharing 
			NULL,           // default security attributes
			OPEN_EXISTING,  // opens existing pipe 
			0,              // default attributes 
			NULL);          // no template file 
							// Break if the pipe handle is valid. 

		if (hPipe != INVALID_HANDLE_VALUE)
			break;

		// Exit if an error other than ERROR_PIPE_BUSY occurs. 

		if (GetLastError() != ERROR_PIPE_BUSY)
		{
			_tprintf(TEXT("Could not open pipe. GLE=%d\n"), GetLastError());
			return -1;
		}

		// All pipe instances are busy, so wait for 20 seconds. 

		if (!WaitNamedPipe(lpszPipename, 20000))
		{
			printf(L"Could not open pipe: 20 second wait timed out.");
			return -1;
		}
	}

	// The pipe connected; change to message-read mode. 
	dwMode = PIPE_READMODE_MESSAGE;
	fSuccess = SetNamedPipeHandleState(
		hPipe,    // pipe handle 
		&dwMode,  // new pipe mode 
		NULL,     // don't set maximum bytes 
		NULL);    // don't set maximum time 
	if (!fSuccess)
	{
		_tprintf(TEXT("SetNamedPipeHandleState failed. GLE=%d\n"), GetLastError());
		return -1;
	}

	return 0;
}
Пример #20
0
		bool PipeClient::Connect(int timeout)
		{
			if(!WaitNamedPipe(m_path.c_str(), (DWORD) timeout))
				return false;

			if((m_pipe = CreateFile(m_path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL)) ==
				INVALID_HANDLE_VALUE)
				return false;

			return true;
		}
Пример #21
0
PIPECLINETHANDLE NamedPipeClientConnect(char * pName, unsigned long commID, PPIPERECVCB pPipeRecvCB)
{
   PIPECLINETHANDLE pipeClientHandle = NULL;
   BOOL bFlag = FALSE;
   if(pName == NULL || commID <= 0) return pipeClientHandle;
   if(!WaitNamedPipe(pName, NMPWAIT_WAIT_FOREVER)) return pipeClientHandle;
   {
      pipeClientHandle = (PIPECLINETHANDLE)malloc(sizeof(NAMEDPIPECLIENT));
      memset(pipeClientHandle, 0, sizeof(NAMEDPIPECLIENT));
      pipeClientHandle->pPipeRecvCB = pPipeRecvCB;
      pipeClientHandle->commID = commID;
      pipeClientHandle->pipeRecvThreadRun = TRUE;
      pipeClientHandle->pipeRecvThreadHandle = CreateThread(NULL, 0, PipeClientRecvThreadStart,pipeClientHandle, 0, NULL);
      if(!pipeClientHandle->pipeRecvThreadHandle)
      {
         pipeClientHandle->pipeRecvThreadRun = FALSE;
         goto done;
      }

      pipeClientHandle->hPipe = CreateFile(pName, GENERIC_READ |GENERIC_WRITE,
         0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
      if(INVALID_HANDLE_VALUE == pipeClientHandle->hPipe)
      {
         pipeClientHandle->isConnected = FALSE;
         goto done;
      }

      {
         DWORD dwMode = PIPE_READMODE_MESSAGE | PIPE_NOWAIT;
         SetNamedPipeHandleState(pipeClientHandle->hPipe, &dwMode, NULL, NULL);
      }

      pipeClientHandle->isConnected = TRUE;

      {
         IPCINTERMSG ipcInterMsg;
         ipcInterMsg.interCmdKey = IPC_CONNECT;
         ipcInterMsg.interParams.commID = commID;
         bFlag = NamedPipeClientGNSend(pipeClientHandle, INTER_MSG, (char *)&ipcInterMsg, sizeof(IPCINTERMSG));
         if(!bFlag) goto done;
      }

      bFlag =TRUE;
   }
   
done:
   if(!bFlag && pipeClientHandle)
   {
      NamedPipeClientDisconnect(pipeClientHandle);
     /* free(pipeClientHandle);*/
      pipeClientHandle = NULL;
   }
   return pipeClientHandle;
}
Пример #22
0
BOOL DOKANAPI DokanMountControl(PDOKAN_CONTROL Control) {
  HANDLE pipe;
  DWORD readBytes;
  DWORD pipeMode;

  for (;;) {
    pipe = CreateFile(DOKAN_CONTROL_PIPE, GENERIC_READ | GENERIC_WRITE, 0, NULL,
                      OPEN_EXISTING, 0, NULL);
    if (pipe != INVALID_HANDLE_VALUE) {
      break;
    }

    DWORD error = GetLastError();
    if (error == ERROR_PIPE_BUSY) {
      if (!WaitNamedPipe(DOKAN_CONTROL_PIPE, NMPWAIT_USE_DEFAULT_WAIT)) {
        DbgPrint("DokanMountControl: DokanMounter service : ERROR_PIPE_BUSY\n");
        return FALSE;
      }
      continue;
    } else if (error == ERROR_ACCESS_DENIED) {
      DbgPrint("DokanMountControl: Failed to connect DokanMounter service: "
               "access denied\n");
      return FALSE;
    } else {
      DbgPrint(
          "DokanMountControl: Failed to connect DokanMounter service: %d\n",
          GetLastError());
      return FALSE;
    }
  }

  pipeMode = PIPE_READMODE_MESSAGE | PIPE_WAIT;

  if (!SetNamedPipeHandleState(pipe, &pipeMode, NULL, NULL)) {
    DbgPrint("DokanMountControl: Failed to set named pipe state: %d\n",
             GetLastError());
    CloseHandle(pipe);
    return FALSE;
  }

  if (!TransactNamedPipe(pipe, Control, sizeof(DOKAN_CONTROL), Control,
                         sizeof(DOKAN_CONTROL), &readBytes, NULL)) {
    DbgPrint("DokanMountControl: Failed to transact named pipe: %d\n",
             GetLastError());
  }

  CloseHandle(pipe);
  if (Control->Status != DOKAN_CONTROL_FAIL) {
    return TRUE;
  } else {
    return FALSE;
  }
}
Пример #23
0
// Подключение к серверу ---------------------------------------------------------------------------------------------------------
int  ConnectToServer() {

  // Ждем возможности подключения
  while (1) {
    if (WaitNamedPipe(chPipeName, NMPWAIT_WAIT_FOREVER)) break;
  }

  // На всякий случай :)
  CloseHandle(hPipe);

  // Создаем канал-клиент
  hPipe = CreateFile(
            chPipeName,           // Имя канала
            GENERIC_READ |        // Доступ к записи и чтению
            GENERIC_WRITE,
            0,                    // Без слвместного использования
            NULL,                 // Обычные аттрибуты защиты
            OPEN_EXISTING,        // Открыть существующий канал
            FILE_FLAG_OVERLAPPED, // Асинхронный Ввод/Вывод
            NULL );

  // Удалось подключится к серверу
  if (hPipe != INVALID_HANDLE_VALUE) {

    // Говорим об этом пользователю
    printf("You connected to server.\n");

    // Задаем первое сообщение - информация о клиенте
    // Считаем размер сообщения
    dwToWrite  = (strlen("Client's name  : Bovin Alexandr\n") + 1) * sizeof(TCHAR);

    // Посылаем сообщение
    WriteFile(hPipe, "Client's name  : Bovin Alexandr\n", dwToWrite, &dwTransfered, &oOverlapped[0]);

    // Устанавливаем статус клиента к записи
    dwState = WRITING_STATE;

    // Есть выполняющиеся операции
    PendingIO = TRUE;

    return 1;
  }

  // Выходим если ошибка отлична от ошибки - канал занят
  if (GetLastError() != ERROR_PIPE_BUSY) {
    printf("Could not open pipe!\n");
    getch();
    return 0;
  }

  return 0;

} // ConnectToServer -------------------------------------------------------------------------------------------------------------
Пример #24
0
	HANDLE ___pipeopen(){
		while (1){
			if ((hdPipe = CreateFile(pipeName,GENERIC_READ|GENERIC_WRITE,0,
				NULL,OPEN_EXISTING,0,NULL))!=INVALID_HANDLE_VALUE)
				break;
			if (GetLastError()!=ERROR_PIPE_BUSY) {
				Func_FastPMNTS(_T("%s Error! (%ld)\n"),__func__,GetLastError());
				return INVALID_HANDLE_VALUE;
			}
			WaitNamedPipe(pipeName, 2000);
		}
		return hdPipe;
	}
Пример #25
0
bool CRemoteCacheLink::InternalEnsurePipeOpen ( CAutoFile& hPipe
											  , const CString& pipeName) const
{
	if (hPipe)
		return true;

	int tryleft = 2;

	while (!hPipe && tryleft--)
	{

		hPipe = CreateFile(
							pipeName,                       // pipe name
							GENERIC_READ |                  // read and write access
							GENERIC_WRITE,
							0,                              // no sharing
							NULL,                           // default security attributes
							OPEN_EXISTING,                  // opens existing pipe
							FILE_FLAG_OVERLAPPED,           // default attributes
							NULL);                          // no template file
		if ((!hPipe) && (GetLastError() == ERROR_PIPE_BUSY))
		{
			// TGitCache is running but is busy connecting a different client.
			// Do not give up immediately but wait for a few milliseconds until
			// the server has created the next pipe instance
			if (!WaitNamedPipe (pipeName, 50))
			{
				continue;
			}
		}
	}

	if (hPipe)
	{
		// The pipe connected; change to message-read mode.
		DWORD dwMode;

		dwMode = PIPE_READMODE_MESSAGE;
		if(!SetNamedPipeHandleState(
			hPipe,    // pipe handle
			&dwMode,  // new pipe mode
			NULL,     // don't set maximum bytes
			NULL))    // don't set maximum time
		{
			CTraceToOutputDebugString::Instance()(__FUNCTION__ ": SetNamedPipeHandleState failed");
			hPipe.CloseHandle();
		}
	}

	return hPipe;
}
Пример #26
0
bool QueryData::QueryByPipe(LPSVDBQUERY lpquery,LPDBQUERY lpdbquery,void **pret,S_UINT &len,string addr,S_UINT timeout)
{
#ifdef	WIN32

	DWORD to= (timeout==-1)? NMPWAIT_WAIT_FOREVER : timeout*1000;


	if(WaitNamedPipe(m_pipename,to)==0)
	{
		return false;
	}


	
	HANDLE hand=::CreateFile(m_pipename,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,
		OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
	if(hand!=INVALID_HANDLE_VALUE)
	{
		if(!Pipe_Send(hand,(void *)lpquery,sizeof(SVDBQUERY)))
		{
			::CloseHandle(hand);
			return false;
		}


		if(!Pipe_Send(hand,(void*)lpdbquery,sizeof(DBQUERY)))
		{
			::CloseHandle(hand);
			return false;
		}


		if(!Pipe_Recev(hand,pret,len))
		{
			::CloseHandle(hand);
			return false;
		}

	}else
	{
		return false;
	}

	::CloseHandle(hand);

#else

#endif
	return true;

}
static bool open_server_connection(nvqr_handle_t *handle, pid_t pid)
{
#if defined(_WIN32)
    char *name = nvqr_ipc_server_pipe_name(pid);
    int i;
    const int max_retries = 3;

    for (i = 0, *handle = INVALID_HANDLE_VALUE;
         i < max_retries && *handle == INVALID_HANDLE_VALUE;
         i++) {
        *handle = CreateFile(
          (LPCSTR)(LPCTSTR)name,
          GENERIC_WRITE,  // write access
          0,              // no sharing
          NULL,           // default security attributes
          OPEN_EXISTING,  // opens existing pipe
          0,              // default attributes
          NULL);          // no template file

        if (*handle == INVALID_HANDLE_VALUE &&
            GetLastError() == ERROR_PIPE_BUSY) {
            WaitNamedPipe((LPCSTR)(LPCSTR)name, 10000);
        }
    }
    free(name);

    return *handle != INVALID_HANDLE_VALUE;
#else
    bool connected = false;

    *handle = socket(PF_UNIX, SOCK_STREAM, 0);
    if (*handle != -1) {
        struct sockaddr_un addr;
        int len;

        memset(&addr, 0, sizeof(addr));
        addr.sun_family = AF_UNIX;
        len = nvqr_ipc_get_socket_name(addr.sun_path,
                                       sizeof(addr.sun_path), pid);
        if (len >= sizeof(addr.sun_path)) {
            fprintf(stderr, "Warning: socket name for pid %ld truncated - "
                            "name collision may be possible.", (long) pid);
        }
        connected = connect(*handle, (struct sockaddr *) &addr,
                            sizeof(addr)) == 0;
    }

    return connected;
#endif
}
StatsServerMessage* NTServerMessage::connectStatsChannel(const char* name)
{
    HANDLE hPipe;
    int nIndex = 0;
    int nTrialCount = 5;
    for (nIndex = 0; nIndex < nTrialCount; ++nIndex)
    {
        DWORD dwAccess = GENERIC_READ | GENERIC_WRITE;
        DWORD dwShared = FILE_SHARE_READ | FILE_SHARE_WRITE;
        DWORD dwFlags = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
        hPipe = CreateFile(name,
                           dwAccess,
                           dwShared,
                           NULL,        // Security Attribute
                           OPEN_EXISTING,
                           dwFlags, // File Attribute
                           NULL);
        if (hPipe != INVALID_HANDLE_VALUE)
            break;              // Got Connected successfully
        if (GetLastError() != ERROR_PIPE_BUSY)
        {
            // Unable to connect.
            return 0;
        }
        int waitTime = 2000;    // 2 seconds
        if (!WaitNamedPipe(name, waitTime))
        {
            // Instance of pipe is not available
            return 0;
        }
        // continue
    }
    if (hPipe == INVALID_HANDLE_VALUE)
        return 0;
    DWORD dwPipeMode = PIPE_READMODE_MESSAGE;
    BOOL fSuccess = SetNamedPipeHandleState(hPipe,
                                            &dwPipeMode,
                                            NULL, // lpMaxCollectionCount
                                            NULL);// lpCollectDataTimeout
    if (!fSuccess)
    {
        // Unable to setup pipe message option
        CloseHandle(hPipe);
        return 0;
    }
    StatsServerMessage* statsMsgChannel = 0;
    statsMsgChannel = new StatsServerMessage(hPipe);
    return statsMsgChannel;
}
Пример #29
0
static bool send_command_pipe(const mount_params* params, QByteArray &err)
{
    DWORD  mode, written, total = 0;
    const wchar_t* pipename = PIPE_NAME;
    HANDLE hPipe = CreateFile(pipename, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

    while (hPipe == INVALID_HANDLE_VALUE)
    {
        if (GetLastError() != ERROR_PIPE_BUSY)
        {
            err = "Unable to connect with mount service.";
            return false;
        }
        if (!WaitNamedPipe(PIPE_NAME, 2000))
        {
            err = "Unable to comunicate with mount service.";
            return false;
        }
        hPipe = CreateFile(pipename, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    }

    mode = PIPE_READMODE_BYTE;
    if (SetNamedPipeHandleState(hPipe, &mode,  NULL, NULL))
    {
        while (total < sizeof(mount_params))
        {
            if (!WriteFile(hPipe, (void*)((char*)params+total), sizeof(mount_params)-total, &written, NULL))
            {
                err = "Communication with mount service is broken.";
                break;
            }
            total += written;
        }
        FlushFileBuffers(hPipe);
    }

    CloseHandle(hPipe);

    if (total != sizeof(mount_params))
    {
        err = "Communication with mount service is incomplete.";
        return false;
    }

    err = "";
    return true;
}
//-----------------------------------------------------------------------------
// FcgiServerChannel::connect
//-----------------------------------------------------------------------------
PRStatus FcgiServerChannel::connect(PRIntervalTime timeoutVal)
{
    // Try to connect
#ifdef XP_WIN32
    if (config->udsName) {
        PRBool pipeBusy = PR_TRUE;
        while(pipeBusy) {
            HANDLE newFd = CreateFile(config->procInfo.bindPath,   // pipe name
                               GENERIC_READ | GENERIC_WRITE, // read and write access
                               FILE_SHARE_WRITE | FILE_SHARE_READ,              // sharing
                               NULL,           // default security attributes
                               OPEN_ALWAYS,  // opens existing pipe or creates a new one
                               FILE_FLAG_OVERLAPPED,              // default attributes
                               NULL);          // no template file


            // Break if the pipe handle is valid.
            if (newFd != INVALID_HANDLE_VALUE) {
                fd = PR_ImportFile((int)newFd);
                return PR_SUCCESS;
            }

            if (!WaitNamedPipe(config->procInfo.bindPath, PR_IntervalToMilliseconds(timeoutVal))) {
                 return PR_FAILURE;
            }

            if (GetLastError() != ERROR_PIPE_BUSY) {
                pipeBusy = PR_FALSE;
            }
        }

        return PR_FAILURE;

    } else {
#endif // XP_WIN32
    if (!fd)
        return PR_FAILURE;

    PRStatus rv = PR_Connect(fd, &(config->procInfo.addr), timeoutVal);
    return rv;

#ifdef XP_WIN32
    }
#endif // XP_WIN32

}