A Windows named pipe implementation written in pure Go.

Related tags

Network npipe
Overview

npipe Build status GoDoc

Package npipe provides a pure Go wrapper around Windows named pipes.

Windows named pipe documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365780

Note that the code lives at https://github.com/natefinch/npipe (v2 branch) but should be imported as gopkg.in/natefinch/npipe.v2 (the package name is still npipe).

npipe provides an interface based on stdlib's net package, with Dial, Listen, and Accept functions, as well as associated implementations of net.Conn and net.Listener. It supports rpc over the connection.

Notes

  • Deadlines for reading/writing to the connection are only functional in Windows Vista/Server 2008 and above, due to limitations with the Windows API.

  • The pipes support byte mode only (no support for message mode)

Examples

The Dial function connects a client to a named pipe:

conn, err := npipe.Dial(`\\.\pipe\mypipename`)
if err != nil {
	<handle error>
}
fmt.Fprintf(conn, "Hi server!\n")
msg, err := bufio.NewReader(conn).ReadString('\n')
...

The Listen function creates servers:

ln, err := npipe.Listen(`\\.\pipe\mypipename`)
if err != nil {
	// handle error
}
for {
	conn, err := ln.Accept()
	if err != nil {
		// handle error
		continue
	}
	go handleConnection(conn)
}

Variables

var ErrClosed = PipeError{"Pipe has been closed.", false}

ErrClosed is the error returned by PipeListener.Accept when Close is called on the PipeListener.

type PipeAddr

type PipeAddr string

PipeAddr represents the address of a named pipe.

func (PipeAddr) Network

func (a PipeAddr) Network() string

Network returns the address's network name, "pipe".

func (PipeAddr) String

func (a PipeAddr) String() string

String returns the address of the pipe

type PipeConn

type PipeConn struct {
    // contains filtered or unexported fields
}

PipeConn is the implementation of the net.Conn interface for named pipe connections.

func Dial

func Dial(address string) (*PipeConn, error)

Dial connects to a named pipe with the given address. If the specified pipe is not available, it will wait indefinitely for the pipe to become available.

The address must be of the form \.\pipe<name> for local pipes and \\pipe<name> for remote pipes.

Dial will return a PipeError if you pass in a badly formatted pipe name.

Examples:

// local pipe
conn, err := Dial(`\\.\pipe\mypipename`)

// remote pipe
conn, err := Dial(`\\othercomp\pipe\mypipename`)

func DialTimeout

func DialTimeout(address string, timeout time.Duration) (*PipeConn, error)

DialTimeout acts like Dial, but will time out after the duration of timeout

func (*PipeConn) Close

func (c *PipeConn) Close() error

Close closes the connection.

func (*PipeConn) LocalAddr

func (c *PipeConn) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*PipeConn) Read

func (c *PipeConn) Read(b []byte) (int, error)

Read implements the net.Conn Read method.

func (*PipeConn) RemoteAddr

func (c *PipeConn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*PipeConn) SetDeadline

func (c *PipeConn) SetDeadline(t time.Time) error

SetDeadline implements the net.Conn SetDeadline method. Note that timeouts are only supported on Windows Vista/Server 2008 and above

func (*PipeConn) SetReadDeadline

func (c *PipeConn) SetReadDeadline(t time.Time) error

SetReadDeadline implements the net.Conn SetReadDeadline method. Note that timeouts are only supported on Windows Vista/Server 2008 and above

func (*PipeConn) SetWriteDeadline

func (c *PipeConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements the net.Conn SetWriteDeadline method. Note that timeouts are only supported on Windows Vista/Server 2008 and above

func (*PipeConn) Write

func (c *PipeConn) Write(b []byte) (int, error)

Write implements the net.Conn Write method.

type PipeError

type PipeError struct {
    // contains filtered or unexported fields
}

PipeError is an error related to a call to a pipe

func (PipeError) Error

func (e PipeError) Error() string

Error implements the error interface

func (PipeError) Temporary

func (e PipeError) Temporary() bool

Temporary implements net.AddrError.Temporary()

func (PipeError) Timeout

func (e PipeError) Timeout() bool

Timeout implements net.AddrError.Timeout()

type PipeListener

type PipeListener struct {
    // contains filtered or unexported fields
}

PipeListener is a named pipe listener. Clients should typically use variables of type net.Listener instead of assuming named pipe.

func Listen

func Listen(address string) (*PipeListener, error)

Listen returns a new PipeListener that will listen on a pipe with the given address. The address must be of the form \.\pipe<name>

Listen will return a PipeError for an incorrectly formatted pipe name.

func (*PipeListener) Accept

func (l *PipeListener) Accept() (net.Conn, error)

Accept implements the Accept method in the net.Listener interface; it waits for the next call and returns a generic net.Conn.

func (*PipeListener) AcceptPipe

func (l *PipeListener) AcceptPipe() (*PipeConn, error)

AcceptPipe accepts the next incoming call and returns the new connection.

func (*PipeListener) Addr

func (l *PipeListener) Addr() net.Addr

Addr returns the listener's network address, a PipeAddr.

func (*PipeListener) Close

func (l *PipeListener) Close() error

Close stops listening on the address. Already Accepted connections are not closed.

Issues
  • Make Go RPC work through a duplex npipe.

    Make Go RPC work through a duplex npipe.

    The catch here is that Go RPC server continuously polls for new requests (has a blocking read going on), even while a request is running (and a reply is written back to the pipe). There are two reasons why this does not work out of the box:

    1. The current os.File implementation uses a Mutex to protect the file offset it is writing to / reading from, so if a blocking Read is going on, it will keep the mutex locked.
    2. Windows cannot read and write to the same file handle concurrently unless overlapped I/O is used.

    Also, there is the minor issue that any broken pipe error is silently being eaten by os.File.Read().

    My patch switches npipe to use ReadFile and WriteFile instead of os.File, passing an Overlapped structure to do overlapped I/O. I've also added a new test case TestGoRPC() to test Go RPC over the named pipe implementation.

    opened by aeckleder 4
  • Correctly handle error_no_data

    Correctly handle error_no_data

    When a client connects to a server and immediately disconnects, accept will return with an error_no_data, which is inconsistent with the behavior of other go Listeners. This patch will make Accept() ignore error_no_data, since there is nothing to do in that case anyway.

    opened by aeckleder 3
  • does not build on linux (expected?)

    does not build on linux (expected?)

    Hello,

    This builds and runs well on Windows 10 but produces an error on any linux install:

    [email protected]:~/Projects/named/client$ go build
    # _/home/johnnyb/Projects/named/client
    ./client.go:12:15: undefined: npipe.Dial
    [email protected]:~/Projects/named/client$ cat -n client.go
         1  package main
         2
         3  import (
         4          "bufio"
         5          "fmt"
         6
         7          "gopkg.in/natefinch/npipe.v2"
         8  )
         9
        10  // Use Dial to connect to a server and read messages from it.
        11  func main() {
        12          conn, err := npipe.Dial(`\\.\pipe\mypipe`)
        13          if err != nil {
        14                  // handle error
        15          }
        16          if _, err := fmt.Fprintln(conn, "Hi server!"); err != nil {
        17                  // handle error
        18          }
        19          r := bufio.NewReader(conn)
        20          msg, err := r.ReadString('\n')
        21          if err != nil {
        22                  // handle eror
        23          }
        24          fmt.Println(msg)
        25  }
    

    Is this expected? Since it' pure Go I was hoping it would work on both OS's. I do a fair amount of Go building on both platforms so the linux Go env is sane.

    Thanks!

    JB

    opened by Omortis 2
  • Protect PipeListener with a mutex.

    Protect PipeListener with a mutex.

    There's a race condition in which PipeListener.Accept and PipeListener.Close are called from separate goroutines. Either method can mutate the state of the PipeListener (l.closed, l.handler). These sections need to be protected with a mutex.

    opened by cmars 2
  • fix a race condition in PipeListener

    fix a race condition in PipeListener

    There was an obvious race between PipeListener's Accept and Close modifying l.closed, found with go test -race, and a less obvious race that if someone calls Close before we call connectnamedpipe, the connect would hang forever. Now we have a lock over the whole of Accept and Close (except while doing WaitSingleObject, which will corrently return an error when we Close), so Close can't screw up connect named pipe.

    opened by natefinch 1
  • Test race fixes

    Test race fixes

    Depends on #17. This fixes all the go test -race ./... errors in the v2 branch, but TestGoRPC still randomly hangs on waitForCompletion -- which tells me there's possibly still an issue with concurrent goroutines in Accept() and Close().

    @natefinch @gabriel-samfira Any ideas?

    opened by cmars 0
  • Communication to server by sending structure

    Communication to server by sending structure

    Hi,

    My requirement is to connect to server. Send the some data in structure. Server will update the signature and send back to client(i am client) as structure. Server is in c++ and they used piped for connection.

    if _, err := fmt.Fprintln(conn, dat); err != nil { //error } by using this i can send the structure value or map.

    But how can I receive the value in structure from server? Please guide.

    opened by Santanu234 0
  • Fix the bug closing same windows handler twice.

    Fix the bug closing same windows handler twice.

    The overlapped.HEvent has been closed in PipeListener.Close and reset to 0. But close again in PipeListener.AcceptPipe with origin HEvent. So that throw a panic which cannot be recovered.

    opened by Tjolk072 0
  • Fix the bug closing same windows handler twice.

    Fix the bug closing same windows handler twice.

    The overlapped.HEvent has been closed in PipeListener.Close and reset to 0. But close again in PipeListener.AcceptPipe with origin HEvent. So that throw a panic which cannot be recovered.

    opened by lnkyan 0
Owner
Nate Finch
Author of gorram, lumberjack, pie, gnorm, mage, and others. https://twitter.com/natethefinch
Nate Finch
A QUIC implementation in pure go

A QUIC implementation in pure Go quic-go is an implementation of the QUIC protocol in Go. It implements the IETF QUIC draft-29 and draft-32. Version c

Lucas Clemente 6.9k Jun 30, 2022
Pure Go implementation of the WebRTC API

Pion WebRTC A pure Go implementation of the WebRTC API New Release Pion WebRTC v3.0.0 has been released! See the release notes to learn about new feat

Pion 9.5k Jul 3, 2022
Pure Go implementation of the WebRTC API

Pure Go implementation of the WebRTC API

Pion 9.5k Jun 26, 2022
🚀 gnet is a high-performance, lightweight, non-blocking, event-driven networking framework written in pure Go./ gnet 是一个高性能、轻量级、非阻塞的事件驱动 Go 网络框架。

English | ???? 中文 ?? Introduction gnet is an event-driven networking framework that is fast and lightweight. It makes direct epoll and kqueue syscalls

Andy Pan 6.6k Jun 30, 2022
Snugger is a light weight but fast network recon scanner that is written from pure golang

Snugger is a light weight but fast network recon scanner that is written from pure golang. with this scann you can ARP your network, port scan hosts and host lists, as well as scan for BSSId

RE43P3R 2 May 19, 2022
Command-line tool and library for Windows remote command execution in Go

WinRM for Go Note: if you're looking for the winrm command-line tool, this has been splitted from this project and is available at winrm-cli This is a

Brice Figureau 365 Jun 19, 2022
Automatically spawn a reverse shell fully interactive for Linux or Windows victim

Girsh (Golang Interactive Reverse SHell) Who didn't get bored of manually typing the few lines to upgrade a reverse shell to a full interactive revers

null 265 Jun 27, 2022
tidal discord rich presence for windows

discordtidal Remember when Discord added a Spotify integration and all of your friends started having fun with it, but then being the weirdo you are,

Nick 12 Jun 1, 2022
EDR-Recon scans Windows services, drivers, processes, registry for installed EDRs.

EDR-Recon EDR-Recon scans Windows services, drivers, processes, registry for installed EDRs. Install Binary Download the latest release from the relea

FourCore Labs 365 Jun 15, 2022
Optimize Windows's network/NIC driver settings for NewTek's NDI(Network-Device-Interface).

windows-ndi-optimizer[WIP] Optimize Windows's network/NIC driver settings for NewTek's NDI(Network-Device-Interface). How it works This is batchfile d

Nil Hiiragi 3 Apr 15, 2022
🦄️ 🎃 👻 Clash Premium 规则集(RULE-SET),兼容 ClashX Pro、Clash for Windows 客户端。

简介 本项目生成适用于 Clash Premium 内核的规则集(RULE-SET),同时适用于所有使用 Clash Premium 内核的 Clash 图形用户界面(GUI)客户端。使用 GitHub Actions 北京时间每天早上 6:30 自动构建,保证规则最新。 说明 本项目规则集(RUL

Loyalsoldier 4.9k Jun 28, 2022
Go wrapper around Device Console Windows tool.

go-devcon Go wrapper around the Windows Device Console (devcon.exe). go install github.com/mikerourke/go-devcon Introduction Here's a brief overview

Mike Rourke 0 Nov 4, 2021
Automatically update your Windows hosts file with the WSL2 VM IP address

Automatically update your Windows hosts file with the WSL2 VM IP address

null 1.3k Jun 28, 2022
Downloads the Windows 10 wallpapers provided by Microsoft.

microsoft-wallpapers Preparation Prepare an input file that contains a list of links from the Microsoft website that lead to wallpapers. This list is

River Wooley 0 Nov 29, 2021
A pair of local reverse proxies (one in Windows, one in Linux) for Tailscale on WSL2

tailscale-wsl2 TL;DR Running two reverse proxies (one in Windows, one in the WSL2 Linux VM), the Windows Tailscale daemon can be accessed via WSL2: $

Danny Hermes 23 Jun 16, 2022
Resolved the issue that Windows cannot detect the Internet even if it does have an Internet connection.

win-connect 中文文档 Background This program is built to resolved the issue that Windows cannot detect the Internet even if it does have an Internet conne

null 0 Dec 19, 2021
Simple reverse shell to avoid Windows defender and kaspersky detection

Windows-ReverseShell Simple reverse shell to avoid Windows defender, kaspersky d

赵公子 11 Jun 9, 2022
A simple Go library to toggle on and off pac(proxy auto configuration) for Windows, MacOS and Linux

pac pac is a simple Go library to toggle on and off pac(proxy auto configuration

null 0 Dec 26, 2021
Pure-Go library for cross-platform local peer discovery using UDP multicast :woman: :repeat: :woman:

peerdiscovery Pure-go library for cross-platform thread-safe local peer discovery using UDP multicast. I needed to use peer discovery for croc and eve

Zack 546 Jun 20, 2022