func newUnixTransport(keys string) (transport, error) { var err error t := new(unixTransport) abstract := getKey(keys, "abstract") path := getKey(keys, "path") switch { case abstract == "" && path == "": return nil, errors.New("dbus: invalid address (neither path nor abstract set)") case abstract != "" && path == "": t.UnixConn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: "@" + abstract, Net: "unix"}) if err != nil { return nil, err } return t, nil case abstract == "" && path != "": t.UnixConn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: path, Net: "unix"}) if err != nil { return nil, err } return t, nil default: return nil, errors.New("dbus: invalid address (both path and abstract set)") } }
// DialServer dials a Unix Domain Socket where a server is listening and // returns a client to the server. func DialServer(uid string) (*Client, error) { // Have the client start listening for responses from the server. clientUID := uuid.New() clientPath := path.Join(os.TempDir(), clientUID) outConn, err := net.ListenUnixgram(udsType, &net.UnixAddr{clientPath, udsType}) if err != nil { return nil, err } // Dial the server. log.Infof("client: dialing the server") setupConn, err := net.DialUnix( udsType, nil, &net.UnixAddr{path.Join(os.TempDir(), uid), udsType}, ) if err != nil { return nil, err } log.Infof("client: sending uid to server") if err := SetupEncode(clientUID, setupConn); err != nil { return nil, err } setupConn.Close() // Get the socket the server is going to listen on. out := bufio.NewReader(outConn) inUUID, err := SetupDecode(out) if err != nil { return nil, err } log.Infof("client: received server uid for conn") // Dial the server. in, err := net.DialUnix( udsType, nil, &net.UnixAddr{path.Join(os.TempDir(), inUUID), udsType}, ) if err != nil { return nil, err } log.Infof("client: dialed server") c := &Client{ inConn: in, outConn: out, reqCh: make(chan request, 50), responses: make(map[uint64]chan response), } go c.send() go c.receive() return c, nil }
// SdNotify sends a message to the init daemon. It is common to ignore the error. // If `unsetEnvironment` is true, the environment variable `NOTIFY_SOCKET` // will be unconditionally unset. // // It returns one of the following: // (false, nil) - notification not supported (i.e. NOTIFY_SOCKET is unset) // (false, err) - notification supported, but failure happened (e.g. error connecting to NOTIFY_SOCKET or while sending data) // (true, nil) - notification supported, data has been sent func SdNotify(unsetEnvironment bool, state string) (sent bool, err error) { socketAddr := &net.UnixAddr{ Name: os.Getenv("NOTIFY_SOCKET"), Net: "unixgram", } // NOTIFY_SOCKET not set if socketAddr.Name == "" { return false, nil } if unsetEnvironment { err = os.Unsetenv("NOTIFY_SOCKET") } if err != nil { return false, err } conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr) // Error connecting to NOTIFY_SOCKET if err != nil { return false, err } defer conn.Close() _, err = conn.Write([]byte(state)) // Error sending the message if err != nil { return false, err } return true, nil }
func ConnectDisplay(addr string) (ret *Display, err error) { runtime_dir := os.Getenv("XDG_RUNTIME_DIR") if runtime_dir == "" { return nil, errors.New("XDG_RUNTIME_DIR not set in the environment.") } if addr == "" { addr = os.Getenv("WAYLAND_DISPLAY") } if addr == "" { addr = "wayland-0" } addr = runtime_dir + "/" + addr ctx := &Connection{} ctx.objects = make(map[ProxyId]Proxy) ctx.currentId = 0 ctx.dispatchRequest = make(chan bool) ctx.exit = make(chan bool) ctx.conn, err = net.DialUnix("unix", nil, &net.UnixAddr{addr, "unix"}) if err != nil { return nil, err } ret = NewDisplay(ctx) // dispatch events in separate gorutine go ctx.run() return ret, nil }
// Notify sends a message to the init daemon. It is common to ignore the error. func Notify(state string) error { socketAddr := &net.UnixAddr{ Name: os.Getenv("NOTIFY_SOCKET"), Net: "unixgram", } if socketAddr.Name == "" { return ErrNotifyNoSocket } switch socketAddr.Name[0] { case '@', '/': default: return ErrNotifyNoSocket } conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr) if err != nil { return err } defer logx.LogReturnedErr(conn.Close, nil, "failed to close connection") _, err = conn.Write([]byte(state)) if err != nil { return err } return nil }
// returns a new BusConnection. func BusConnect(path string, bh busHandler, rh readHandler) (conn *BusConnection, err error) { // check if file exists. if not, bail. _, err = os.Lstat(path) if err != nil { return } // resolve the address. addr, err := net.ResolveUnixAddr("unix", path) if err != nil { return } // connect. unixConn, err := net.DialUnix("unix", nil, addr) if err != nil { return } // create the connection. conn = &BusConnection{ path: path, socket: unixConn, incoming: bufio.NewReader(unixConn), outgoing: bufio.NewWriter(unixConn), busHandler: bh, readHandler: rh, Connected: true, } return }
func newProxy(src, dst string) (*unixProxy, error) { os.Remove(src) // start listening local, err := net.ListenUnixgram("unixgram", &net.UnixAddr{ Name: src, Net: "unixgram", }) if err != nil { return nil, err } remote, err := net.DialUnix("unixgram", nil, &net.UnixAddr{ Name: dst, Net: "unixgram", }) if err != nil { return nil, err } return &unixProxy{ local: local, remote: remote, }, nil }
func (_ *ListenerSuite) TestListenUnix(c *C) { addr, _ := net.ResolveUnixAddr("unix", "/tmp/go_test_socket") cfg := &conf.ListenerConf{ Name: "local", Ports: []*conf.PortConf{ &conf.PortConf{ Type: "unix", Addr: addr, }, }, } ll := listener.NewListener(cfg) ll.SetHandler(echoHandler) ll.Start() time.Sleep(50 * time.Millisecond) cc, err := net.DialUnix("unix", nil, addr) c.Assert(err, IsNil) testEchoConnection(c, cc) cc.Close() ll.Stop() }
func NewUnixgramServer(t lotf.Tail, raddr *net.UnixAddr) (*DgramServer, error) { conn, err := net.DialUnix("unixgram", nil, raddr) if err != nil { return nil, err } return &DgramServer{t, io.WriteCloser(conn)}, nil }
func Connect(path string) (conn *Connection, err error) { // check if file exists. if not, bail. _, err = os.Lstat(path) if err != nil { return } // resolve the address addr, err := net.ResolveUnixAddr("unix", path) if err != nil { return } // connect unixConn, err := net.DialUnix("unix", nil, addr) if err != nil { return } conn = &Connection{ path: path, socket: unixConn, incoming: bufio.NewReader(unixConn), } return }
// Attempt to hijack session previously running bot func (irc *IrcCon) HijackSession() bool { unaddr, err := net.ResolveUnixAddr("unix", irc.unixastr) if err != nil { irc.Log(LWarning, "could not resolve unix socket") return false } con, err := net.DialUnix("unix", nil, unaddr) if err != nil { fmt.Println("Couldnt restablish connection, no prior bot.") fmt.Println(err) return false } ncon, err := sendfd.RecvFD(con) if err != nil { panic(err) } netcon, err := net.FileConn(ncon) if err != nil { panic(err) } irc.reconnect = true irc.con = netcon return true }
// OpenTPM opens a channel to the TPM at the given path. If the file is a // device, then it treats it like a normal TPM device, and if the file is a // Unix domain socket, then it opens a connection to the socket. func OpenTPM(path string) (io.ReadWriteCloser, error) { // If it's a regular file, then open it var rwc io.ReadWriteCloser fi, err := os.Stat(path) if err != nil { return nil, err } if fi.Mode()&os.ModeDevice != 0 { var f *os.File f, err = os.OpenFile(path, os.O_RDWR, 0600) if err != nil { return nil, err } rwc = io.ReadWriteCloser(f) } else if fi.Mode()&os.ModeSocket != 0 { uc, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: path, Net: "unix"}) if err != nil { return nil, err } rwc = io.ReadWriteCloser(uc) } else { return nil, fmt.Errorf("unsupported TPM file mode %s", fi.Mode().String()) } return rwc, nil }
// setupSockets sets up the sockets used to communicate between the client // and the server. If successful it spins up another goroutine to handle // all communication from that client. func (s *Server) setupSockets(remoteID string) { log.Infof("server: dialing client socket") out, err := net.DialUnix( udsType, nil, &net.UnixAddr{path.Join(os.TempDir(), remoteID), udsType}, ) if err != nil { log.Infof("problem dialing client's socket: %s", err) return } log.Infof("server: preparing to listen on new socket") uid := uuid.New() p := path.Join(os.TempDir(), uid) in, err := net.ListenUnixgram(udsType, &net.UnixAddr{p, udsType}) if err != nil { out.Close() log.Infof("could not listen on domain socket %q: %s", p, err) return } log.Infof("server: sending a uid to the client") if err := SetupEncode(uid, out); err != nil { out.Close() log.Infof("problem encoding UUIDv4 for setup: %s", err) return } go s.serveConn(in, out) }
// Send sends a message to the init daemon. It is common to ignore the error. // // This function differs from that in github.com/coreos/go-systemd/daemon in // that that code closes the socket after each call, and so won't work in a // chroot. This function keeps the socket open; so long as it is called at // least once before chrooting, it can continue to be used. // // May return ErrNoSocket. func NotifySend(state string) error { sdNotifyMutex.Lock() defer sdNotifyMutex.Unlock() if !sdNotifyInited { sdNotifyInited = true socketAddr := &net.UnixAddr{ Name: os.Getenv("NOTIFY_SOCKET"), Net: "unixgram", } if socketAddr.Name == "" { return ErrNoSocket } conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr) if err != nil { return err } sdNotifySocket = conn } if sdNotifySocket == nil { return ErrNoSocket } _, err := sdNotifySocket.Write([]byte(state)) return err }
func connectViaUnix(c *Client, remote *RemoteConfig) error { c.BaseURL = "http://unix.socket" c.BaseWSURL = "ws://unix.socket" c.Transport = "unix" uDial := func(network, addr string) (net.Conn, error) { // The arguments 'network' and 'addr' are ignored because // they are the wrong information. // addr is generated from BaseURL which becomes // 'unix.socket:80' which is certainly not what we want. // handle: // unix:///path/to/socket // unix:/path/to/socket // unix:path/to/socket path := strings.TrimPrefix(remote.Addr, "unix:") if strings.HasPrefix(path, "///") { // translate unix:///path/to, to just "/path/to" path = path[2:] } raddr, err := net.ResolveUnixAddr("unix", path) if err != nil { return nil, err } return net.DialUnix("unix", nil, raddr) } c.Http.Transport = &http.Transport{Dial: uDial} c.websocketDialer.NetDial = uDial c.Remote = remote st, err := c.ServerStatus() if err != nil { return err } c.Certificate = st.Environment.Certificate return nil }
func main() { flag.Usage = help cmd := "help" switch av0 := path.Base(os.Args[0]); av0 { case "tao_run", "tao_list", "tao_stop", "tao_kill": cmd = av0[4:] flag.Parse() default: // Get options before the command verb flag.Parse() // Get command verb if flag.NArg() > 0 { cmd = flag.Arg(0) } // Get options after the command verb if flag.NArg() > 1 { flag.CommandLine.Parse(flag.Args()[1:]) } } sockPath := path.Join(hostPath(), "admin_socket") conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: sockPath, Net: "unix"}) options.FailIf(err, "Can't connect to host admin socket") defer conn.Close() client := tao.NewLinuxHostAdminClient(conn) switch cmd { case "help": help() case "run": runHosted(&client, flag.Args()) case "stop": for _, s := range flag.Args() { var subprin auth.SubPrin _, err := fmt.Sscanf(s, "%v", &subprin) options.FailIf(err, "Not a subprin: %s", s) err = client.StopHostedProgram(subprin) options.FailIf(err, "Could not stop %s", s) } case "kill": for _, s := range flag.Args() { var subprin auth.SubPrin options.FailIf(err, "Not a subprin: %s", s) err = client.KillHostedProgram(subprin) options.FailIf(err, "Could not kill %s", s) } case "list": names, pids, err := client.ListHostedPrograms() options.FailIf(err, "Can't list hosted programs") for i, p := range pids { fmt.Printf("pid=%d subprin=%v\n", p, names[i]) } fmt.Printf("%d hosted programs\n", len(pids)) default: options.Usage("Unrecognized command: %s", cmd) } return }
func send(req string, extendTimeout bool) ([]string, error) { conn, err := net.DialUnix("unix", nil, &net.UnixAddr{socketPath, "unix"}) if err != nil { return nil, err } defer conn.Close() writeDeadline := time.Now().Add(clientTimeout) conn.SetWriteDeadline(writeDeadline) _, err = conn.Write([]byte(req)) if err != nil { logger.Errorf("Failed to write request: %v.", err) return nil, err } readDeadline := time.Now().Add(clientTimeout) if extendTimeout { readDeadline = time.Now().Add(extendedTimeout) } conn.SetReadDeadline(readDeadline) data, err := ioutil.ReadAll(conn) if err != nil { logger.Errorf("Failed to read response: %v.", err) return nil, err } resp := strings.Split(string(data), "\n") err = checkHeader(resp) if err != nil { logger.Errorf("Request failed: %v.", err) return nil, err } return resp[1:], nil }
// Netcat is called with: // // lxd netcat /path/to/unix/socket // // and does unbuffered netcatting of to socket to stdin/stdout. Any arguments // after the path to the unix socket are ignored, so that this can be passed // directly to rsync as the sync command. func Netcat(args []string) error { if len(args) < 2 { return fmt.Errorf("Bad arguments %q", args) } uAddr, err := net.ResolveUnixAddr("unix", args[1]) if err != nil { return err } conn, err := net.DialUnix("unix", nil, uAddr) if err != nil { return err } wg := sync.WaitGroup{} wg.Add(1) go func() { io.Copy(os.Stdout, conn) conn.Close() wg.Done() }() go func() { io.Copy(conn, os.Stdin) }() wg.Wait() return nil }
func Dial(path string) (*rpcplus.Client, error) { conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Net: "unix", Name: path}) if err != nil { return nil, err } return NewClient(conn), nil }
func runFDForward(cCmd *cobra.Command, args []string) (exit int) { if len(args) != 1 { stderr("Provide a single argument") return 1 } to := args[0] raddr, err := net.ResolveUnixAddr("unix", to) if err != nil { stderr("Unable to use %q as unix address: %v", to, err) return 1 } sock, err := net.DialUnix("unix", nil, raddr) if err != nil { stderr("Failed dialing remote address: %v", err) return } defer sock.Close() errchan := make(chan error) go cp(os.Stdout, sock, errchan) go cp(sock, os.Stdin, errchan) select { case err := <-errchan: if err != nil { stderr("Encountered error during copy: %v", err) return 1 } } return }
func (s *UnixListenerTestSuite) TestSendAndUnmarshalConnData() { if !s.NoError(s.Listener.Start(), "should start successfully") { return } in := map[string]string{ "foo": "bar", } addr, _ := net.ResolveUnixAddr("unix", s.Listener.Addr()) conn, err := net.DialUnix("unix", nil, addr) if !s.NoError(err, "failed to dial listener") { return } _ = acomm.SendConnData(conn, in) _ = conn.Close() lConn := s.Listener.NextConn() if !s.NotNil(lConn, "connection should not be nil") { return } out := map[string]string{} s.NoError(acomm.UnmarshalConnData(lConn, &out), "should succeed unmarshalling") s.Equal(in, out, "should have unmarshaled the correct data") s.Listener.DoneConn(lConn) }
func Notify(state string, fds ...int) { ns := os.Getenv("NOTIFY_SOCKET") if ns == "" { return } addr := &net.UnixAddr{ Name: ns, Net: "unixgram", } conn, err := net.DialUnix("unixgram", nil, addr) if err != nil { return } defer conn.Close() if len(fds) > 0 { rights := syscall.UnixRights(fds...) conn.WriteMsgUnix([]byte(state), rights, nil) } else { conn.Write([]byte(state)) } }
func Connect(address string, factory MsgFactory, log *logging.Logger, handlers ...interface{}) (*MsgConn, error) { md, err := createDispatcher(log, handlers...) if err != nil { return nil, err } conn, err := net.DialUnix("unix", nil, &net.UnixAddr{address, "unix"}) if err != nil { return nil, err } done := make(chan bool) idGen := newIdGen(done) mc := &MsgConn{ log: log, conn: conn, disp: md, oob: createOobBuffer(), factory: factory, idGen: idGen, respMan: newResponseManager(), onClose: func() { md.close() close(done) }, } go mc.readLoop() return mc, nil }
func newIpcClient(cfg IpcConfig, codec codec.Codec) (*ipcClient, error) { c, err := net.DialUnix("unix", nil, &net.UnixAddr{cfg.Endpoint, "unix"}) if err != nil { return nil, err } return &ipcClient{cfg.Endpoint, c, codec, codec.New(c)}, nil }
// Dial implements the PipeDialer Dial method func (d *dialer) Dial() (mangos.Pipe, error) { conn, err := net.DialUnix("unix", nil, d.addr) if err != nil { return nil, err } return mangos.NewConnPipeIPC(conn, d.sock) }
func dialUnix(path string) (transport, error) { addr, err := net.ResolveUnixAddr("unix", path) conn, err := net.DialUnix("unix", nil, addr) if err != nil { return nil, err } return &unixTransport{conn}, nil }
func dialUnix(port string, tlscfg *tls.Config) (net.Conn, error) { tlscfg = nil addr, err := net.ResolveUnixAddr("unix", port) if err != nil { return nil, err } return net.DialUnix("unix", nil, addr) }
func TestListenUnixgramReadFrom(t *testing.T) { switch runtime.GOOS { case "linux": // run this on linux. default: t.Logf("skipping test on %q", runtime.GOOS) return } // TODO: use mktmp to create this file. path := "/tmp/example.sock" addr, err := net.ResolveUnixAddr("unixgram", path) if err != nil { t.Fatalf("ResolveUnixAddr failed on %v: %v", path, err) return } //var reader *net.UnixConn reader, err := net.DialUnix("unixgram", nil, addr) if err != nil { t.Fatalf("ListenUnix failed on %v: %v", path, err) return } defer reader.Close() // Make something that writes to it. writer, err := net.DialUnix("unixgram", nil, addr) if err != nil { t.Fatalf("DialUnix failed: %v", err) return } defer writer.Close() expected := "Hello world" writer.Write([]byte(expected)) actual := make([]byte, 100) length, _, err := reader.ReadFrom(actual) if err != nil { t.Fatalf("UnixConn.ReadFromfailed: %v", err) } if string(actual[0:length]) != expected { t.Fatalf("Expected %v, got %v", expected, actual) } }
func (self *ipcClient) reconnect() error { self.coder.Close() c, err := net.DialUnix("unix", nil, &net.UnixAddr{self.endpoint, "unix"}) if err == nil { self.coder = self.codec.New(c) } return err }
func shutdown() error { sockPath := path.Join(hostPath(), "admin_socket") conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: sockPath, Net: "unix"}) if err != nil { return err } defer conn.Close() return tao.NewLinuxHostAdminClient(conn).Shutdown() }