ipc_unix.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
  17. package comms
  18. import (
  19. "net"
  20. "os"
  21. "github.com/ethereum/go-ethereum/logger"
  22. "github.com/ethereum/go-ethereum/logger/glog"
  23. "github.com/ethereum/go-ethereum/rpc/codec"
  24. "github.com/ethereum/go-ethereum/rpc/shared"
  25. )
  26. func newIpcClient(cfg IpcConfig, codec codec.Codec) (*ipcClient, error) {
  27. c, err := net.DialUnix("unix", nil, &net.UnixAddr{cfg.Endpoint, "unix"})
  28. if err != nil {
  29. return nil, err
  30. }
  31. return &ipcClient{cfg.Endpoint, c, codec, codec.New(c)}, nil
  32. }
  33. func (self *ipcClient) reconnect() error {
  34. self.coder.Close()
  35. c, err := net.DialUnix("unix", nil, &net.UnixAddr{self.endpoint, "unix"})
  36. if err == nil {
  37. self.coder = self.codec.New(c)
  38. }
  39. return err
  40. }
  41. func startIpc(cfg IpcConfig, codec codec.Codec, initializer func(conn net.Conn) (shared.EthereumApi, error)) error {
  42. os.Remove(cfg.Endpoint) // in case it still exists from a previous run
  43. l, err := net.ListenUnix("unix", &net.UnixAddr{Name: cfg.Endpoint, Net: "unix"})
  44. if err != nil {
  45. return err
  46. }
  47. os.Chmod(cfg.Endpoint, 0600)
  48. go func() {
  49. for {
  50. conn, err := l.AcceptUnix()
  51. if err != nil {
  52. glog.V(logger.Error).Infof("Error accepting ipc connection - %v\n", err)
  53. continue
  54. }
  55. id := newIpcConnId()
  56. glog.V(logger.Debug).Infof("New IPC connection with id %06d started\n", id)
  57. api, err := initializer(conn)
  58. if err != nil {
  59. glog.V(logger.Error).Infof("Unable to initialize IPC connection - %v\n", err)
  60. conn.Close()
  61. continue
  62. }
  63. go handle(id, conn, api, codec)
  64. }
  65. os.Remove(cfg.Endpoint)
  66. }()
  67. glog.V(logger.Info).Infof("IPC service started (%s)\n", cfg.Endpoint)
  68. return nil
  69. }