Example #1
0
/*
 * Open the service pipe and initialize service I/O.
 * Failure is not fatal.
 */
static BOOL
InitServiceIO (service_io_t *s)
{
    DWORD dwMode = PIPE_READMODE_MESSAGE;
    CLEAR(*s);

    /* auto-reset event used for signalling i/o completion*/
    s->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
    if (!s->hEvent)
    {
        return FALSE;
    }

    s->pipe = CreateFile(_T("\\\\.\\pipe\\openvpn\\service"),
                GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);

    if ( !s->pipe                                               ||
         s->pipe == INVALID_HANDLE_VALUE                        ||
         !SetNamedPipeHandleState(s->pipe, &dwMode, NULL, NULL)
       )
    {
        CloseServiceIO (s);
        return FALSE;
    }

    return TRUE;
}
Example #2
0
bool WinProcessImpl::DoReadFromPipe(HANDLE pipe, wxString& buff)
{
    DWORD dwRead;
    DWORD dwMode;
    DWORD dwTimeout;
    memset(m_buffer, 0, sizeof(m_buffer));

    // Make the pipe to non-blocking mode
    dwMode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
    dwTimeout = 1000;
    SetNamedPipeHandleState(pipe,
                            &dwMode,
                            NULL,
                            &dwTimeout);

    BOOL bRes = ReadFile( pipe, m_buffer, 65536, &dwRead, NULL);
    if ( bRes ) {
        wxString tmpBuff;
        // Success read
        m_buffer[dwRead/sizeof(char)] = 0;
        tmpBuff = wxString(m_buffer, wxConvUTF8);
        if (tmpBuff.IsEmpty() && dwRead > 0) {
            //conversion failed
            tmpBuff = wxString::From8BitData(m_buffer);
        }
        buff << tmpBuff;
        return true;
    }

    return false;
}
Example #3
0
static PyObject *
win32_SetNamedPipeHandleState(PyObject *self, PyObject *args)
{
    HANDLE hNamedPipe;
    PyObject *oArgs[3];
    DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
    int i;

    if (!PyArg_ParseTuple(args, F_HANDLE "OOO",
                          &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2]))
        return NULL;

    PyErr_Clear();

    for (i = 0 ; i < 3 ; i++) {
        if (oArgs[i] != Py_None) {
            dwArgs[i] = PyInt_AsUnsignedLongMask(oArgs[i]);
            if (PyErr_Occurred())
                return NULL;
            pArgs[i] = &dwArgs[i];
        }
    }

    if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2]))
        return PyErr_SetFromWindowsErr(0);

    Py_RETURN_NONE;
}
Example #4
0
void Pipe::connectToPipe(const std::string &pipeName)
{
    //Console::log("Connecting to " + pipeName);
    closePipe();
    bool done = false;
    while(!done)
    {
        m_handle = CreateFileA( 
            pipeName.c_str(),             // pipe name 
            GENERIC_READ |                // read and write access 
            GENERIC_WRITE, 
            0,                            // no sharing 
            nullptr,                         // default security attributes
            OPEN_EXISTING,                // opens existing pipe 
            0,                            // default attributes 
            nullptr);                        // no template file
        if(m_handle != INVALID_HANDLE_VALUE)
        {
            done = true;
        }
        Sleep(100);
    }
    //cout << "Connected" << endl;

    //DWORD mode = PIPE_READMODE_MESSAGE;
    DWORD mode = PIPE_READMODE_BYTE;
    BOOL success = SetNamedPipeHandleState( 
        m_handle,  // pipe handle 
        &mode,    // new pipe mode 
        nullptr,     // don't set maximum bytes 
        nullptr);    // don't set maximum time 
    MLIB_ASSERT_STR(success != FALSE, "SetNamedPipeHandleState failed in Pipe::ConnectToPipe");
}
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;
}
Example #6
0
bool WinProcessImpl::Write(const wxString& buff)
{
    DWORD dwMode;
    DWORD dwTimeout;

    wxUnusedVar(dwTimeout);
    char  chBuf[4097];

    wxString tmpCmd = buff;
    tmpCmd = tmpCmd.Trim().Trim(false);
    tmpCmd += wxT("\r\n");

    strcpy(chBuf, tmpCmd.mb_str());

    // Make the pipe to non-blocking mode
    dwMode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
    dwTimeout = 30000;
    SetNamedPipeHandleState(hChildStdinWrDup,
                            &dwMode,
                            NULL,
                            NULL);             // Timeout of 30 seconds
    DWORD dwWritten;
    if (!WriteFile(hChildStdinWrDup, chBuf, (unsigned long)strlen(chBuf), &dwWritten, NULL))
        return false;
    return true;
}
Example #7
0
inline Try<Nothing> nonblock(int fd)
{
  if (net::is_socket(fd)) {
    const u_long non_block_mode = 1;
    u_long mode = non_block_mode;

    int result = ioctlsocket(fd, FIONBIO, &mode);
    if (result != NO_ERROR) {
      return WindowsSocketError();
    }
  } else {
    // Extract handle from file descriptor.
    HANDLE handle = reinterpret_cast<HANDLE>(::_get_osfhandle(fd));
    if (handle == INVALID_HANDLE_VALUE) {
      return WindowsError("Failed to get `HANDLE` for file descriptor");
    }

    if (GetFileType(handle) == FILE_TYPE_PIPE) {
      DWORD pipe_mode = PIPE_NOWAIT;
      if (SetNamedPipeHandleState(handle, &pipe_mode, nullptr, nullptr)) {
        return WindowsError();
      }
    }
  }

  return Nothing();
}
Example #8
0
void Pipe::ConnectToPipe(const String &PipeName)
{
    ClosePipe();
    bool Done = false;
    while(!Done)
    {
        _Handle = CreateFile( 
            PipeName.CString(),           // 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(_Handle != INVALID_HANDLE_VALUE)
        {
            Done = true;
        }
        Sleep(100);
    }

    DWORD Mode = PIPE_READMODE_MESSAGE;
    BOOL Success = SetNamedPipeHandleState( 
        _Handle,  // pipe handle 
        &Mode,    // new pipe mode 
        NULL,     // don't set maximum bytes 
        NULL);    // don't set maximum time 
    Assert(Success != FALSE, "SetNamedPipeHandleState failed in Pipe::ConnectToPipe");
}
Example #9
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;
}
Example #10
0
int main()
{
    DWORD mode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT;
    if (SetNamedPipeHandleState(GetStdHandle(STD_INPUT_HANDLE), &mode, NULL, NULL))
        return 0;
    return GetLastError();
}
Example #11
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;
}
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case ID_BTN_CONNECT:
			char addr[100];
			GetDlgItemText(hWnd, ID_PIPE_ADDR, addr, 100);
			
			if (strlen(addr) > 0)
			{
				g_pipeName = "\\\\" + std::string(addr) + "\\pipe\\smpipe";
			}
			//delete[] addr;
			break;
		case ID_BTN_SEND:
			g_hPipe = CreateFile(g_pipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
			
			if (g_hPipe == INVALID_HANDLE_VALUE || !SetNamedPipeHandleState(g_hPipe, &g_dwMode, NULL, NULL))
				break;
			GetDlgItemText(hWnd, ID_STR_LINE, g_message, 255);
			DWORD dwBytesWritten;
			WriteFile(g_hPipe, g_message, 255, &dwBytesWritten, NULL);
			CloseHandle(g_hPipe);
			break;
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY: //вызывается, когда жмём крестик закрытия
		//changed
		//очистка ресурсов
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Example #13
0
	DWORD ___pipesentmessage(const TCHAR * szSent){
		DWORD dwReserved=PIPE_READMODE_MESSAGE;
	    if (!SetNamedPipeHandleState(hdPipe,&dwReserved,NULL,NULL))
			Func_FastPMNTS(_T("SetNamedPipeHandleState() Error! (%ld)\n"),GetLastError());
	    if (!WriteFile(hdPipe,szSent,(lstrlen(szSent)+1)*sizeof(TCHAR),&dwReserved,NULL))
			Func_FastPMNTS(_T("WriteFile() Error! (%ld)\n"),GetLastError());
	    return GetLastError();
	}
Example #14
0
int fcgi_init(void)
{
	if (!is_initialized) {
#ifndef _WIN32
		sa_t sa;
		socklen_t len = sizeof(sa);
#endif
		zend_hash_init(&fcgi_mgmt_vars, 0, NULL, fcgi_free_mgmt_var_cb, 1);
		fcgi_set_mgmt_var("FCGI_MPXS_CONNS", sizeof("FCGI_MPXS_CONNS")-1, "0", sizeof("0")-1);

		is_initialized = 1;
#ifdef _WIN32
# if 0
		/* TODO: Support for TCP sockets */
		WSADATA wsaData;

		if (WSAStartup(MAKEWORD(2,0), &wsaData)) {
			fprintf(stderr, "Error starting Windows Sockets.  Error: %d", WSAGetLastError());
			return 0;
		}
# endif
		if ((GetStdHandle(STD_OUTPUT_HANDLE) == INVALID_HANDLE_VALUE) &&
		    (GetStdHandle(STD_ERROR_HANDLE)  == INVALID_HANDLE_VALUE) &&
		    (GetStdHandle(STD_INPUT_HANDLE)  != INVALID_HANDLE_VALUE)) {
			char *str;
			DWORD pipe_mode = PIPE_READMODE_BYTE | PIPE_WAIT;
			HANDLE pipe = GetStdHandle(STD_INPUT_HANDLE);

			SetNamedPipeHandleState(pipe, &pipe_mode, NULL, NULL);

			str = getenv("_FCGI_SHUTDOWN_EVENT_");
			if (str != NULL) {
				HANDLE shutdown_event = (HANDLE) atoi(str);
				if (!CreateThread(NULL, 0, fcgi_shutdown_thread,
				                  shutdown_event, 0, NULL)) {
					return -1;
				}
			}
			str = getenv("_FCGI_MUTEX_");
			if (str != NULL) {
				fcgi_accept_mutex = (HANDLE) atoi(str);
			}
			return is_fastcgi = 1;
		} else {
			return is_fastcgi = 0;
		}
#else
		errno = 0;
		if (getpeername(0, (struct sockaddr *)&sa, &len) != 0 && errno == ENOTCONN) {
			fcgi_setup_signals();
			return is_fastcgi = 1;
		} else {
			return is_fastcgi = 0;
		}
#endif
	}
	return is_fastcgi;
}
Example #15
0
// this thread works in a fire-and-forget fashion, it's started and then just runs
static DWORD WINAPI read_named_pipe(void *opaque) {
	const char *pipe_name = "\\\\.\\pipe\\tinkerforge-brick-daemon-debug-log";
	HANDLE hpipe;
	DWORD mode = PIPE_READMODE_MESSAGE;
	LogPipeMessage pipe_message;
	DWORD bytes_read;

	(void)opaque;

	append_debug_meta_message("Connecting to Brick Daemon...");

	for (;;) {
		_debug_connected = 0;

		update_status_bar();

		for (;;) {
			hpipe = CreateFile(pipe_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

			if (hpipe != INVALID_HANDLE_VALUE) {
				break;
			}

			Sleep(250);
		}

		if (!SetNamedPipeHandleState(hpipe, &mode, NULL, NULL)) {
			CloseHandle(hpipe);

			continue;
		}

		_debug_connected = 1;

		update_status_bar();
		append_debug_meta_message("Connected to Brick Daemon");

		for (;;) {
			if (!ReadFile(hpipe, &pipe_message, sizeof(pipe_message), &bytes_read, NULL)) {
				append_debug_meta_message("Disconnected from Brick Daemon, reconnecting...");
				CloseHandle(hpipe);

				break;
			}

			if (bytes_read == sizeof(pipe_message) && pipe_message.length == sizeof(pipe_message)) {
				// enforce that strings are NUL-terminated
				pipe_message.file[sizeof(pipe_message.file) - 1] = '\0';
				pipe_message.function[sizeof(pipe_message.function) - 1] = '\0';
				pipe_message.message[sizeof(pipe_message.message) - 1] = '\0';

				append_debug_pipe_message(&pipe_message);
			}
		}
	}

	return 0;
}
Example #16
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;
}
Example #17
0
static int JaxerStartup(int &argc, char **argv)
{
    // tell manager I am up and establish the communication channel for later use

    // return 0 on success, none-0 if fails.
    // program should terminate if this function fails.

    // TODO: we should get this from the cmdline and get rid of the env var

    char *pipename = getenv("JAXER_PIPENAME");
    if (pipename == NULL) {
        gJaxerLog.Log(eFATAL, "Must be launched by Jaxer Server Manager.\n");
        fprintf(stderr, "Must be launched by Jaxer Server Manager.\n");
        return 1;
    }

#ifdef _WIN32
    // Manager is waiting for us to connect back to it.  Don't keep it waiting.
    g_pipe = CreateFile(pipename,
                        GENERIC_READ | GENERIC_WRITE,
                        0,
                        NULL,
                        OPEN_EXISTING,
                        FILE_FLAG_OVERLAPPED,
                        NULL);
    if (g_pipe == INVALID_HANDLE_VALUE) {
        gJaxerLog.Log(eFATAL, "Invalid handle value when creating the pipe");
        return 1;
    }

    // Put pipe into message mode.
    DWORD mode = PIPE_READMODE_MESSAGE;
    if (!SetNamedPipeHandleState(g_pipe, &mode, NULL, NULL)) {
        gJaxerLog.Log(eFATAL, "Unable to put pipe into message mode.");
        return 1;
    }
#else
    // Manager created a Unix-domain socket pair and passed one of the sockets
    // as standard input.
    g_pipe = 0;

    // Let Manager know we're alive.
    char byte = 1;
    int rc;
    do {
        rc = send(g_pipe, &byte, 1, 0);
    } while (rc < 0 && errno == EINTR);
    if (rc < 0) {
        gJaxerLog.Log(eFATAL, "Error in sending 'alive status' to Jaxer Manager");
        return 1;
    } else if (rc == 0) {
        gJaxerLog.Log(eFATAL, "Manager stop talking to us immediately");
        return 1;
    }
#endif
    return 0;
}
Example #18
0
HRESULT PipeStream::SetState(DWORD* mode, DWORD* max_collections,
                             DWORD* collect_timeout) {
  if (!IsValid())
    return E_HANDLE;

  if (!SetNamedPipeHandleState(handle_, mode, max_collections, collect_timeout))
    return HRESULT_FROM_LAST_ERROR();

  return S_OK;
}
Example #19
0
PONY_EXTERN_C_BEGIN

/**
 * Create an anonymous pipe for communicating with another (most likely child)
 * process. Create and return C FDs for the handles and return those via the
 * uint32 ptrs provided. The outgoing flag determines whether the pipe handles
 * will be oriented for outgoing (near=write) or incoming (near=read).
 * Return true if OK, false if not.
 *
 * This MS Doc is the most generally useful reference on working with
 * child processes and pipes:
 *   https://docs.microsoft.com/en-us/windows/desktop/procthread/creating-a-child-process-with-redirected-input-and-output
 *
 * Also useful is that anonymous pipes (for child processes in/out/err) are
 * just named pipes with special names, and can use the same functions:
 *   https://msdn.microsoft.com/en-us/library/windows/desktop/aa365787(v=vs.85).aspx
 */
PONY_API uint32_t ponyint_win_pipe_create(uint32_t* near_fd, uint32_t* far_fd, bool outgoing) {
    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;  // default to inherit, clear the flag on the near hnd later

    HANDLE read_hnd;
    HANDLE write_hnd;
    if (!CreatePipe(&read_hnd, &write_hnd, &sa, 0)) {
        return false;
    }

    DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
    if (outgoing) {
        SetHandleInformation(write_hnd, HANDLE_FLAG_INHERIT, 0);
        SetNamedPipeHandleState(write_hnd, &mode, NULL, NULL);
        *near_fd = _open_osfhandle((intptr_t)write_hnd, 0);
        *far_fd = _open_osfhandle((intptr_t)read_hnd, 0);
    } else {
        SetHandleInformation(read_hnd, HANDLE_FLAG_INHERIT, 0);
        SetNamedPipeHandleState(read_hnd, &mode, NULL, NULL);
        *near_fd = _open_osfhandle((intptr_t)read_hnd, 0);
        *far_fd = _open_osfhandle((intptr_t)write_hnd, 0);
    }
    return true;
}
nsresult
NamedPipeInfo::Connect(const nsACString& aPath)
{
  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);

  HANDLE pipe;
  nsAutoCString path(aPath);

  pipe = CreateFileA(path.get(),
                     GENERIC_READ | GENERIC_WRITE,
                     FILE_SHARE_READ | FILE_SHARE_WRITE,
                     nullptr,
                     OPEN_EXISTING,
                     FILE_FLAG_OVERLAPPED,
                     nullptr);

  if (pipe == INVALID_HANDLE_VALUE) {
    LOG_NPIO_ERROR("[%p] CreateFile error (%d)", this, GetLastError());
    return NS_ERROR_FAILURE;
  }

  DWORD pipeMode = PIPE_READMODE_MESSAGE;
  if (!SetNamedPipeHandleState(pipe, &pipeMode, nullptr, nullptr)) {
    LOG_NPIO_ERROR("[%p] SetNamedPipeHandleState error (%d)",
                   this,
                   GetLastError());
    CloseHandle(pipe);
    return NS_ERROR_FAILURE;
  }

  nsresult rv = mNamedPipeService->AddDataObserver(pipe, this);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    CloseHandle(pipe);
    return rv;
  }

  HANDLE readEvent = CreateEventA(nullptr, TRUE, TRUE, "NamedPipeRead");
  if (NS_WARN_IF(!readEvent || readEvent == INVALID_HANDLE_VALUE)) {
    CloseHandle(pipe);
    return NS_ERROR_FAILURE;
  }

  HANDLE writeEvent = CreateEventA(nullptr, TRUE, TRUE, "NamedPipeWrite");
  if (NS_WARN_IF(!writeEvent || writeEvent == INVALID_HANDLE_VALUE)) {
    CloseHandle(pipe);
    CloseHandle(readEvent);
    return NS_ERROR_FAILURE;
  }

  mPipe = pipe;
  mReadOverlapped.hEvent = readEvent;
  mWriteOverlapped.hEvent = writeEvent;
  return NS_OK;
}
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;
}
Example #22
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;
}
Example #23
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;
  }
}
Example #24
0
/*
1.初始化fcgi_mgmt_vars相应的字段,主要是fastcgi协议要求的内容,fcgi_mgmt_vars是一个hashtable
2.标记is_initialized=1
3.fcgi_setup_signal初始化信号
*/
int fcgi_init(void)
{
	// 初始化
	if (!is_initialized) {
		zend_hash_init(&fcgi_mgmt_vars, 0, NULL, fcgi_free_mgmt_var_cb, 1);
		
		// FCGI_MPXS_CONNS是fastcgi协议中规定的字段
                // 如果应用不用 多路复用线路(也就是通过每个线路处理并发请求)则为 "0",其他则为"1"
                // come from http://www.myexception.cn/cgi/674116.html
		fcgi_set_mgmt_var("FCGI_MPXS_CONNS", sizeof("FCGI_MPXS_CONNS") - 1, "0", sizeof("0")-1);

		is_initialized = 1;
		
		// win相关
#ifdef _WIN32
# if 0
		/* TODO: Support for TCP sockets */
		WSADATA wsaData;

		if (WSAStartup(MAKEWORD(2,0), &wsaData)) {
			fprintf(stderr, "Error starting Windows Sockets.  Error: %d", WSAGetLastError());
			return 0;
		}
# endif
		{
			char *str;
			DWORD pipe_mode = PIPE_READMODE_BYTE | PIPE_WAIT; // 数据以单独字节的形式从管道中读出 | 			DWORD pipe_mode = PIPE_READMODE_BYTE | PIPE_WAIT; // 数据以单独字节的形式从管道中读出 | 同步操作在等待的时候挂起线程
			HANDLE pipe = GetStdHandle(STD_INPUT_HANDLE);

			SetNamedPipeHandleState(pipe, &pipe_mode, NULL, NULL);

			str = getenv("_FCGI_SHUTDOWN_EVENT_");
			if (str != NULL) {
				HANDLE shutdown_event = (HANDLE) atoi(str);
				if (!CreateThread(NULL, 0, fcgi_shutdown_thread,
				                  shutdown_event, 0, NULL)) {
					return -1;
				}
			}
			str = getenv("_FCGI_MUTEX_");
			if (str != NULL) {
				fcgi_accept_mutex = (HANDLE) atoi(str);
			}
			return 1;
		}
#else
		fcgi_setup_signals();
		return 1;
#endif
	}
	return 1;
}
Example #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;
}
Example #26
0
HRESULT NamedPipeChannel::SetMode(DWORD mode) {
  // drop unsupported flag
  mode &= ~PIPE_NOWAIT;

  base::AutoLock guard(lock_);

  if (!IsValid())
    return E_HANDLE;

  if (!SetNamedPipeHandleState(handle_, &mode, nullptr, nullptr))
    return HRESULT_FROM_WIN32(GetLastError());

  return S_OK;
}
int
set_nonblocking_flag (int desc, bool value)
{
  HANDLE h = (HANDLE) _get_osfhandle (desc);
  if (h == INVALID_HANDLE_VALUE)
    {
      errno = EBADF;
      return -1;
    }
  if (GetFileType (h) == FILE_TYPE_PIPE)
    {
      /* h is a pipe or socket.  */
      DWORD state;
      if (GetNamedPipeHandleState (h, &state, NULL, NULL, NULL, NULL, 0))
        {
          /* h is a pipe.  */
          if ((state & PIPE_NOWAIT) != 0)
            {
              if (value)
                return 0;
              state &= ~PIPE_NOWAIT;
            }
          else
            {
              if (!value)
                return 0;
              state |= PIPE_NOWAIT;
            }
          if (SetNamedPipeHandleState (h, &state, NULL, NULL))
            return 0;
          errno = EINVAL;
          return -1;
        }
      else
        {
          /* h is a socket.  */
          int v = value;
          return ioctl (desc, FIONBIO, &v);
        }
    }
  else
    {
      /* The native Windows API does not support non-blocking on regular
         files.  */
      if (!value)
        return 0;
      errno = ENOTSUP;
      return -1;
    }
}
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;
}
Example #29
0
static int uv_set_pipe_handle(uv_pipe_t* handle, HANDLE pipeHandle) {
  DWORD mode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT;

  if (!SetNamedPipeHandleState(pipeHandle, &mode, NULL, NULL)) {
    return -1;
  }

  if (CreateIoCompletionPort(pipeHandle,
                             LOOP->iocp,
                             (ULONG_PTR)handle,
                             0) == NULL) {
    return -1;
  }

  return 0;
}
Example #30
0
HANDLE RpcEngine::acceptClient() {

	if (!mhServerPipe) {
		return NULL;
	}
	DWORD status;
	DWORD nCount;
	HANDLE events[2];

	nCount = 0;
	events[nCount++] = mhStopEvent;
	events[nCount++] = mhServerPipe;

	status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE);
/*	if (status == WAIT_OBJECT_0) {
		return NULL;
	} else if (status == WAIT_OBJECT_0 +1) {*/
	if (WaitForSingleObject(mhStopEvent, 0) == WAIT_OBJECT_0) {
		WLog_Print(logger_RPCEngine, WLOG_TRACE, "got shutdown signal");
		return NULL;
	}
	if (WaitForSingleObject(mhServerPipe, 0) == WAIT_OBJECT_0) {
		BOOL fConnected;
		DWORD dwPipeMode;

		fConnected = ConnectNamedPipe(mhServerPipe, NULL);

		if (!fConnected)
			fConnected = (GetLastError() == ERROR_PIPE_CONNECTED);

		if (!fConnected) {
			WLog_Print(logger_RPCEngine, WLOG_ERROR, "could not connect client");

			return NULL;
		}

		mhClientPipe = mhServerPipe;

		dwPipeMode = PIPE_WAIT;
		SetNamedPipeHandleState(mhClientPipe, &dwPipeMode, NULL, NULL);
		WLog_Print(logger_RPCEngine, WLOG_TRACE, "connect client with handle %x",mhClientPipe);

		return mhClientPipe;
	}
	return NULL;

}