func UnixAudienceListener(sockaddr string) { fi, err := os.Stat(sockaddr) if err == nil { fmode := fi.Mode() if fmode&os.ModeType == os.ModeSocket { o.Warn("Removing stale socket at %s", sockaddr) os.Remove(sockaddr) } else { o.Fail("%s exists and is not a socket", sockaddr) } } laddr, err := net.ResolveUnixAddr("unix", sockaddr) o.MightFail(err, "Couldn't resolve audience socket address") l, err := net.ListenUnix("unix", laddr) o.MightFail(err, "Couldn't start audience unixsock listener") // Fudge the permissions on the unixsock! fi, err = os.Stat(sockaddr) if err == nil { os.Chmod(sockaddr, fi.Mode()|0777) } else { o.Warn("Couldn't fudge permission on audience socket: %s", err) } // make sure we clean up the unix socket when we die. defer l.Close() defer os.Remove(sockaddr) AudienceListener(l) }
func TestQmpInitTimeout(t *testing.T) { ctx, qc := testQmpEnvironment() go qmpHandler(ctx) t.Log("connecting to ", qc.qmpSockName) ss, err := net.ListenUnix("unix", &net.UnixAddr{qc.qmpSockName, "unix"}) if err != nil { t.Error("fail to setup connect to qmp socket", err.Error()) } c, err := ss.Accept() if err != nil { t.Error("cannot accept qmp socket", err.Error()) } defer ss.Close() defer c.Close() t.Log("connected") time.Sleep(11 * time.Second) ev := <-ctx.Hub if ev.Event() != hypervisor.ERROR_INIT_FAIL { t.Error("should got an fail event") } t.Log("finished timeout test") }
func unix_coll(_, address string) (Listener, error) { var err error r := new(unix_receiver) r.network = "unix" r.address = address r.listener, err = net.ListenUnix("unix", &net.UnixAddr{address, "unix"}) for err != nil { switch err.(type) { case *net.OpError: if err.(*net.OpError).Err.Error() != "bind: address already in use" { return nil, err } default: return nil, err } if _, r_err := os.Stat(address); r_err != nil { return nil, err } os.Remove(address) r.listener, err = net.ListenUnix("unix", &net.UnixAddr{address, "unix"}) } return r, nil }
func create_socket(l *log.Logger, socket string, uid, gid int, end <-chan struct{}, wg *sync.WaitGroup) *Listener { conn, err := net.ListenUnix("unix", &net.UnixAddr{socket, "unix"}) for err != nil { switch err.(type) { case *net.OpError: if err.(*net.OpError).Err.Error() != "bind: address already in use" { l.Printf("Listen %s : %s", socket, err) } default: l.Printf("Listen %s : %s", socket, err) } if _, r_err := os.Stat(socket); r_err != nil { l.Printf("Lstat %s : %s", socket, err) } os.Remove(socket) conn, err = net.ListenUnix("unix", &net.UnixAddr{socket, "unix"}) } os.Chown(socket, uid, gid) wg.Add(1) return &Listener{conn, end, wg} }
func newUnixServer(keys string, uuid string) (Server, error) { var err error abstract := getKey(keys, "abstract") path := getKey(keys, "path") s := new(unixServer) s.uuid = uuid switch { case abstract == "" && path == "": return nil, errors.New("dbus: invalid address (neither path nor abstract set)") case abstract != "" && path == "": s.listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: "@" + abstract, Net: "unix"}) if err != nil { return nil, err } return s, nil case abstract == "" && path != "": s.listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) if err != nil { return nil, err } return s, nil default: return nil, errors.New("dbus: invalid address (both path and abstract set)") } }
func UnixAudienceListener(sockaddr string, sockmode os.FileMode, sockuid int, sockgid int) { fi, err := os.Stat(sockaddr) if err == nil { if (fi.Mode() & os.ModeSocket) != 0 { os.Remove(sockaddr) } else { o.Fail("%s exists and is not a socket", sockaddr) } } err = os.MkdirAll(path.Dir(sockaddr), 0755) o.MightFail(err, "Couldn't create socket directory") laddr, err := net.ResolveUnixAddr("unix", sockaddr) o.MightFail(err, "Couldn't resolve audience socket address") old_umask := syscall.Umask(0777) defer syscall.Umask(old_umask) l, err := net.ListenUnix("unix", laddr) o.MightFail(err, "Couldn't start audience unixsock listener") if sockuid >= 0 || sockgid >= 0 { err = os.Chown(sockaddr, sockuid, sockgid) o.MightFail(err, "Couldn't chown audience unixsock listener") } err = os.Chmod(sockaddr, sockmode) o.MightFail(err, "Couldn't chmod audience unixsock listener") // make sure we clean up the unix socket when we die. defer l.Close() defer os.Remove(sockaddr) AudienceListener(l) }
func StartClientHandler(tree *ProcessTree, quit chan bool) { path, _ := filepath.Abs(zeusSockName) addr, err := net.ResolveUnixAddr("unix", path) if err != nil { panic("Can't open socket.") } listener, err := net.ListenUnix("unix", addr) if err != nil { ErrorCantCreateListener() } defer listener.Close() connections := make(chan *unixsocket.Usock) go func() { for { if conn, err := listener.AcceptUnix(); err != nil { errorUnableToAcceptSocketConnection() time.Sleep(500 * time.Millisecond) } else { connections <- unixsocket.NewUsock(conn) } } }() for { select { case <-quit: quit <- true return case conn := <-connections: go handleClientConnection(tree, conn) } } }
func daemonIpc(done <-chan struct{}) { if _, err := os.Stat(Config.ClueGetter.IPC_Socket); !os.IsNotExist(err) { err = os.Remove(Config.ClueGetter.IPC_Socket) if err != nil { Log.Fatal(fmt.Sprintf("IPC Socket %s already exists and could not be removed: %s", Config.ClueGetter.IPC_Socket, err.Error())) } } l, err := net.ListenUnix("unix", &net.UnixAddr{Config.ClueGetter.IPC_Socket, "unix"}) if err != nil { Log.Fatal(err) } go func() { <-done l.Close() // Also removes socket file }() for { conn, err := l.AcceptUnix() if err != nil { _, open := <-done if !open { Log.Info("IPC Socket shutting down") break } Log.Fatal("Critical error on IPC Socket: %s", err) } go daemonIpcHandleConn(conn) } }
// ListenUnix announces on the local network address laddr. The network net // must be a: "unix" or "unixpacket". It returns an inherited net.Listener for // the matching network and address, or creates a new one using net.ListenUnix. func (n *Net) ListenUnix(nett string, laddr *net.UnixAddr) (*net.UnixListener, error) { if err := n.inherit(); err != nil { return nil, err } n.mutex.Lock() defer n.mutex.Unlock() // look for an inherited listener for i, l := range n.inherited { if l == nil { // we nil used inherited listeners continue } if isSameAddr(l.Addr(), laddr) { n.inherited[i] = nil n.active = append(n.active, l) return l.(*net.UnixListener), nil } } // make a fresh listener l, err := net.ListenUnix(nett, laddr) if err != nil { return nil, err } n.active = append(n.active, l) return l, nil }
// unixListener returns the listener used for registrations (over unix sock) func unixListener() (net.Listener, error) { s := os.Getenv("LISTEN_FDS") if s != "" { // socket activated lfds, err := strconv.ParseInt(s, 10, 16) if err != nil { return nil, errwrap.Wrap(errors.New("error parsing LISTEN_FDS env var"), err) } if lfds < 1 { return nil, fmt.Errorf("LISTEN_FDS < 1") } return net.FileListener(os.NewFile(uintptr(listenFdsStart), "listen")) } else { dir := filepath.Dir(common.MetadataServiceRegSock) err := os.MkdirAll(dir, 0755) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("failed to create %v", dir), err) } return net.ListenUnix("unix", &net.UnixAddr{ Net: "unix", Name: common.MetadataServiceRegSock, }) } }
func main() { flag.Parse() // Create unix socket addr, err := net.ResolveUnixAddr("unix", *socketPath) if err != nil { log.Fatal(err) } l, err := net.ListenUnix("unix", addr) if err != nil { log.Fatal(err) } // Create server that listens on the socket s := agent.NewServer(l, &accpeter{}) // Setup signal handler to stop Server on various signals s.StopOnSignals(os.Interrupt, syscall.SIGTERM) log.Println("Server listening on", addr.String()) err = s.Serve() if err != nil { log.Fatal(err) } log.Println("Server stopped") }
// ListenUnix announces on the local network address laddr. The network net // must be a: "unix" or "unixpacket". It returns an inherited net.Listener for // the matching network and address, or creates a new one using net.ListenUnix. func (n *nimbleNet) ListenUnix(nett string, laddr *net.UnixAddr) (*net.UnixListener, error) { if err := n.getInheritedListeners(); err != nil { return nil, iodine.New(err, nil) } n.mutex.Lock() defer n.mutex.Unlock() // look for an inherited listener for i, l := range n.inheritedListeners { if l == nil { // we nil used inherited listeners continue } equal := nimbleAddr{l.Addr()}.IsEqual(laddr) if equal { n.inheritedListeners[i] = nil n.activeListeners = append(n.activeListeners, l) return l.(*net.UnixListener), nil } } // make a fresh listener l, err := net.ListenUnix(nett, laddr) if err != nil { return nil, iodine.New(err, nil) } n.activeListeners = append(n.activeListeners, l) return l, nil }
func NewServer(address string, factory MsgFactory, log *logging.Logger, handlers ...interface{}) (*MsgServer, error) { md, err := createDispatcher(log, handlers...) if err != nil { return nil, err } listener, err := net.ListenUnix("unix", &net.UnixAddr{address, "unix"}) if err != nil { md.close() return nil, err } if err := setPassCred(listener); err != nil { return nil, errors.New("Failed to set SO_PASSCRED on listening socket: " + err.Error()) } done := make(chan bool) idGen := newIdGen(done) return &MsgServer{ log: log, disp: md, factory: factory, listener: listener, done: done, idGen: idGen, }, nil }
// StartUnixListener starts up a unix domain socket listener for reconnects to // be sent through func (irc *Bot) StartUnixListener() { unaddr, err := net.ResolveUnixAddr("unix", irc.unixastr) if err != nil { panic(err) } list, err := net.ListenUnix("unix", unaddr) if err != nil { panic(err) } irc.unixlist = list con, err := list.AcceptUnix() if err != nil { fmt.Println("unix listener error: ", err) return } list.Close() fi, err := irc.con.(*net.TCPConn).File() if err != nil { panic(err) } err = sendfd.SendFD(con, fi) if err != nil { panic(err) } select { case <-irc.Incoming: default: close(irc.Incoming) } close(irc.outgoing) }
func startIpc(cfg IpcConfig, codec codec.Codec, api shared.EthereumApi) error { os.Remove(cfg.Endpoint) // in case it still exists from a previous run l, err := net.ListenUnix("unix", &net.UnixAddr{Name: cfg.Endpoint, Net: "unix"}) if err != nil { return err } os.Chmod(cfg.Endpoint, 0600) go func() { for { conn, err := l.AcceptUnix() if err != nil { glog.V(logger.Error).Infof("Error accepting ipc connection - %v\n", err) continue } id := newIpcConnId() glog.V(logger.Debug).Infof("New IPC connection with id %06d started\n", id) go handle(id, conn, api, codec) } os.Remove(cfg.Endpoint) }() glog.V(logger.Info).Infof("IPC service started (%s)\n", cfg.Endpoint) return nil }
// Open opens the transport. func (c Config) Open() (transports.Transport, error) { if c.Name == "" { c.Name = path.Join(os.TempDir(), "telehash-"+randomString(8)+".sock") } if c.Mode == 0 { c.Mode = 0700 } c.Mode &= os.ModePerm c.Mode |= os.ModeSocket laddr, err := net.ResolveUnixAddr("unix", c.Name) if err != nil { return nil, err } listener, err := net.ListenUnix("unix", laddr) if err != nil { return nil, err } err = os.Chmod(laddr.Name, c.Mode) if err != nil { listener.Close() os.Remove(laddr.Name) return nil, err } return &transport{(*unixAddr)(laddr), listener}, nil }
// InitPlugin registers REST endpoints to handle requests from Mesos CNI plugins func InitPlugin(netPlugin *plugin.NetPlugin) { cniLog = log.WithField("plugin", "mesos") cniLog.Infof("starting Mesos CNI server") router := mux.NewRouter() // register handlers for cni plugin subRtr := router.Headers("Content-Type", "application/json").Subrouter() subRtr.HandleFunc(cniapi.MesosNwIntfAdd, httpWrapper(mesosNwIntfAdd)).Methods("POST") subRtr.HandleFunc(cniapi.MesosNwIntfDel, httpWrapper(mesosNwIntfDel)).Methods("POST") router.HandleFunc("/{*}", unknownReq) sockFile := cniapi.ContivMesosSocket os.Remove(sockFile) os.MkdirAll(cniapi.PluginPath, 0700) cniDriverInit(netPlugin) go func() { lsock, err := net.ListenUnix("unix", &net.UnixAddr{Name: sockFile, Net: "unix"}) if err != nil { cniLog.Errorf("Mesos CNI server failed: %s", err) return } cniLog.Infof("Mesos CNI server is listening on %s", sockFile) http.Serve(lsock, router) lsock.Close() cniLog.Infof("Mesos CNI server socket %s closed ", sockFile) }() }
func serveFpr(addr string, s *siegfried.Siegfried) { // remove the socket file if it exists if _, err := os.Stat(addr); err == nil { os.Remove(addr) } uaddr, err := net.ResolveUnixAddr("unix", addr) if err != nil { log.Fatalf("FPR error: failed to get address: %v", err) } lis, err := net.ListenUnix("unix", uaddr) if err != nil { log.Fatalf("FPR error: failed to listen: %v", err) } buf := make([]byte, 4024) for { conn, err := lis.Accept() if err != nil { log.Fatalf("FPR error: bad connection: %v", err) } l, err := conn.Read(buf) if err != nil { conn.Write([]byte("error reading from connection: " + err.Error())) } conn.Write(fpridentify(s, string(buf[:l]))) conn.Close() } }
// NewUserNetwork returns a Network implementation using the QEMU user-space // network stack. This doesn't provide the same level of isolation, but the // meta-data service should be sufficiently isolated. func NewUserNetwork(socketFolder string) (*UserNetwork, error) { n := &UserNetwork{ socketFile: filepath.Join(socketFolder, "meta-"+slugid.Nice()+".sock"), } n.server = &graceful.Server{ Timeout: 35 * time.Second, Server: &http.Server{ Addr: metaDataIP + ":80", Handler: http.HandlerFunc(n.dispatchRequest), }, NoSignalHandling: true, } // Start listening (we handle listener error as a special thing) listener, err := net.ListenUnix("unix", &net.UnixAddr{ Name: n.socketFile, Net: "unix", }) if err != nil { return nil, fmt.Errorf("Failed to listen on %s error: %s", n.socketFile, err) } // Start serving serverDone := make(chan struct{}) n.serverDone = serverDone go func(n *UserNetwork, done chan<- struct{}) { err := n.server.Serve(listener) close(done) if err != nil { panic(fmt.Sprint("Fatal: meta-data service listener failed, error: ", err)) } }(n, serverDone) return n, nil }
func main() { if len(os.Args) != 2 { println("need one argument") return } ua, err := net.ResolveUnixAddr("unix", os.Args[1]) if err != nil { println("resolve unix", err.Error()) return } ul, err := net.ListenUnix("unix", ua) if err != nil { println("listen unix", err.Error()) return } //for { uc, err := ul.AcceptUnix() if err != nil { println("accept", err.Error()) panic("accept") } go func() { r := rand.Int() for { uc.Write([]byte(fmt.Sprintf("%d\n", r))) time.Sleep(time.Second) } }() //} ul.Close() <-(chan int)(nil) }
func (p *Proxy) Listen() error { err := p.cleanup() if err != nil { return err } addr, err := net.ResolveUnixAddr("unix", "/var/run/docker.sock") if err != nil { return err } raw, err := net.ListenUnix("unix", addr) if err != nil { return err } listener := &stoppableListener{ UnixListener: raw, done: p.done, } err = os.Chmod("/var/run/docker.sock", 0777) if err != nil { return err } server := http.Server{ Handler: http.HandlerFunc(p.handler), } return server.Serve(listener) }
// Create socket and channel for nagios notify func GetNotifyChan(nagiosSocketFileName string) <-chan io.ReadCloser { notifyesChan := make(chan io.ReadCloser, 100) // create listener go func() { // remove socket os.Remove(nagiosSocketFileName) // create socket listen, err := net.ListenUnix("unix", &net.UnixAddr{nagiosSocketFileName, "unix"}) if err := os.Chmod(nagiosSocketFileName, 0777); err != nil { log.Panic(err) } if err != nil { log.Panic(err) } // remove socket on normal halt defer os.Remove(nagiosSocketFileName) // accept connection and send it in channel for { conn, err := listen.AcceptUnix() if err != nil { log.Panic(err) } notifyesChan <- conn } }() return notifyesChan }
// ListenUnix announces on the local network address laddr. The network net // must be a: "unix" or "unixpacket". It returns an inherited net.Listener for // the matching network and address, or creates a new one using net.ListenUnix. func (n *minNet) ListenUnix(nett string, laddr *net.UnixAddr) (net.Listener, *probe.Error) { if err := n.getInheritedListeners(); err != nil { return nil, err.Trace() } n.mutex.Lock() defer n.mutex.Unlock() // look for an inherited listener for i, l := range n.inheritedListeners { if l == nil { // we nil used inherited listeners continue } equal := minAddr{l.Addr()}.IsEqual(laddr) if equal { n.inheritedListeners[i] = nil n.activeListeners = append(n.activeListeners, l) return l.(*net.UnixListener), nil } } // make a fresh listener l, err := net.ListenUnix(nett, laddr) if err != nil { return nil, probe.NewError(err) } n.activeListeners = append(n.activeListeners, rateLimitedListener(l, n.connLimit)) return l, nil }
// setupTestServer creates a listener for the rest requests. func setupTestServer() { router := mux.NewRouter() // register handlers for cni t := router.Headers("Content-Type", "application/json").Methods("POST").Subrouter() t.HandleFunc(cniapi.EPAddURL, httpWrapper(stubAddPod)) t.HandleFunc(cniapi.EPDelURL, httpWrapper(stubDeletePod)) driverPath := cniapi.ContivCniSocket os.Remove(driverPath) os.MkdirAll(cniapi.PluginPath, 0700) go func() { l, err := net.ListenUnix("unix", &net.UnixAddr{Name: driverPath, Net: "unix"}) if err != nil { panic(err) } logger.Infof("k8s test plugin listening on %s", driverPath) http.Serve(l, router) l.Close() logger.Infof("k8s test plugin closing %s", driverPath) }() }
func (t *UnixInput) Init(config interface{}) error { var err error t.config = config.(*UnixInputConfig) if !strings.HasPrefix(t.config.Address, "@") { return fmt.Errorf("only ephemeral sockets supported - prefix your path with '@'") } address, err := net.ResolveUnixAddr("unix", t.config.Address) if err != nil { return fmt.Errorf("ResolveUnixAddress failed: %s\n", err.Error()) } t.listener, err = net.ListenUnix("unix", address) if err != nil { return fmt.Errorf("ListenUnix failed: %s\n", err.Error()) } // We're already listening, make sure we clean up if init fails later on. closeIt := true defer func() { if closeIt { t.listener.Close() } }() t.stopChan = make(chan bool) closeIt = false return nil }
func main() { e := New() sckt, err := net.ListenUnix("unix", &net.UnixAddr{socketPath, "unix"}) if err != nil { panic(err) } defer os.Remove(socketPath) defer e.Conn().Close() l := e.Loop(sckt) err = e.LoadConfig(ConfigPath) if err != nil { e.Println(err.Error()) } EVT: for { select { case <-l.pre: <-l.post case msg := <-l.comm: if verbose { e.Println(msg) } case <-l.quit: break EVT } } e.Println("EXITING......\n") }
// createListener creates a new net.UnixListener func (ul *UnixListener) createListener() error { // create directory structure if it does not exist yet directory := filepath.Dir(ul.Addr()) // TODO: Decide on permissions if err := os.MkdirAll(directory, os.ModePerm); err != nil { log.WithFields(log.Fields{ "directory": directory, "perm": os.ModePerm, "error": err, }).Error("failed to create directory for socket") return err } listener, err := net.ListenUnix("unix", ul.addr) if err != nil { log.WithFields(log.Fields{ "addr": ul.Addr(), "error": err, }).Error("failed to create listener") return err } ul.listener = listener return nil }
// NewWorker starts an http server listening on an abstract domain socket // which will be created with the specified name. func NewWorker(config Config) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } if runtime.GOOS != "linux" { return nil, errors.NotSupportedf("os %q", runtime.GOOS) } path := "@" + config.SocketName addr, err := net.ResolveUnixAddr("unix", path) if err != nil { return nil, errors.Annotate(err, "unable to resolve unix socket") } l, err := net.ListenUnix("unix", addr) if err != nil { return nil, errors.Annotate(err, "unable to listen on unix socket") } logger.Debugf("introspection worker listening on %q", path) w := &socketListener{ listener: l, reporter: config.Reporter, done: make(chan struct{}), } go w.serve() go w.run() return w, nil }
func (s *Server) Start() error { c, _ := projects.ConfigDir() socketpath := filepath.Join(c, "projects.socket") addr, err := net.ResolveUnixAddr("unix", socketpath) if err != nil { return err } listener, e := net.ListenUnix("unix", addr) if e != nil { return e } var opts []grpc.ServerOption grpcServer := grpc.NewServer(opts...) messages.RegisterProjectsServer(grpcServer, &projectServer{s.core}) messages.RegisterResourcesServer(grpcServer, &resourcesServer{s.core}) messages.RegisterEventsServer(grpcServer, &eventsServer{s.core}) //s.core.Log.Infof("project daemon started and listening on %s", socketpath) s.server = grpcServer s.listener = listener s.tomb.Go(func() error { return grpcServer.Serve(listener) }) return nil }
func (srv *Server) listenUnix(addr string) (listener, error) { laddr, err := net.ResolveUnixAddr("unix", addr) if err != nil { return nil, err } return net.ListenUnix("unix", laddr) }