1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
|
package varlink
import (
"context"
"encoding/json"
"fmt"
"net"
"os"
"strings"
"sync"
"time"
"github.com/varlink/go/varlink/internal/ctxio"
)
type dispatcher interface {
VarlinkDispatch(ctx context.Context, c Call, methodname string) error
VarlinkGetName() string
VarlinkGetDescription() string
}
type serviceCall struct {
Method string `json:"method"`
Parameters *json.RawMessage `json:"parameters,omitempty"`
More bool `json:"more,omitempty"`
Oneway bool `json:"oneway,omitempty"`
Upgrade bool `json:"upgrade,omitempty"`
}
type serviceReply struct {
Parameters interface{} `json:"parameters,omitempty"`
Continues bool `json:"continues,omitempty"`
Error string `json:"error,omitempty"`
}
// Service represents an active varlink service. In addition to the registered custom varlink Interfaces, every service
// implements the org.varlink.service interface which allows clients to retrieve information about the
// running service.
type Service struct {
vendor string
product string
version string
url string
interfaces map[string]dispatcher
names []string
descriptions map[string]string
running bool
listener net.Listener
conncounter int64
mutex sync.Mutex
protocol string
address string
}
// ServiceTimeoutError helps API users to special-case timeouts.
type ServiceTimeoutError struct{}
func (ServiceTimeoutError) Error() string {
return "service timeout"
}
func (s *Service) getInfo(ctx context.Context, c Call) error {
return c.replyGetInfo(ctx, s.vendor, s.product, s.version, s.url, s.names)
}
func (s *Service) getInterfaceDescription(ctx context.Context, c Call, name string) error {
if name == "" {
return c.ReplyInvalidParameter(ctx, "interface")
}
description, ok := s.descriptions[name]
if !ok {
return c.ReplyInvalidParameter(ctx, "interface")
}
return c.replyGetInterfaceDescription(ctx, description)
}
func (s *Service) HandleMessage(ctx context.Context, conn ReadWriterContext, request []byte) error {
var in serviceCall
err := json.Unmarshal(request, &in)
if err != nil {
return err
}
c := Call{
Conn: conn,
In: &in,
Request: &request,
}
r := strings.LastIndex(in.Method, ".")
if r <= 0 {
return c.ReplyInvalidParameter(ctx, "method")
}
interfacename := in.Method[:r]
methodname := in.Method[r+1:]
if interfacename == "org.varlink.service" {
return s.orgvarlinkserviceDispatch(ctx, c, methodname)
}
// Find the interface and method in our service
iface, ok := s.interfaces[interfacename]
if !ok {
return c.ReplyInterfaceNotFound(ctx, interfacename)
}
return iface.VarlinkDispatch(ctx, c, methodname)
}
// Shutdown shuts down the listener of a running service.
func (s *Service) Shutdown() error {
s.running = false
s.mutex.Lock()
defer s.mutex.Unlock()
if s.listener == nil {
return nil
}
return s.listener.Close()
}
func (s *Service) handleConnection(ctx context.Context, conn net.Conn, wg *sync.WaitGroup) {
defer func() { s.mutex.Lock(); s.conncounter--; s.mutex.Unlock(); wg.Done() }()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ctxConn := ctxio.NewConn(conn)
for {
request, err := ctxConn.ReadBytes(ctx, '\x00')
if err != nil {
break
}
err = s.HandleMessage(ctx, ctxConn, request[:len(request)-1])
if err != nil {
// FIXME: report error
// fmt.Fprintf(os.Stderr, "handleMessage: %v", err)
break
}
}
conn.Close()
}
func (s *Service) teardown() {
s.mutex.Lock()
s.listener = nil
s.running = false
s.protocol = ""
s.address = ""
s.mutex.Unlock()
}
func (s *Service) parseAddress(address string) error {
words := strings.SplitN(address, ":", 2)
if len(words) != 2 {
return fmt.Errorf("Unknown protocol")
}
s.protocol = words[0]
s.address = words[1]
// Ignore parameters after ';'
words = strings.SplitN(s.address, ";", 2)
if words != nil {
s.address = words[0]
}
switch s.protocol {
case "unix":
break
case "tcp":
break
default:
return fmt.Errorf("Unknown protocol")
}
return nil
}
func (s *Service) GetListener() (net.Listener, error) {
s.mutex.Lock()
l := s.listener
s.mutex.Unlock()
return l, nil
}
func (s *Service) setListener(ctx context.Context) error {
l := activationListener()
if l == nil {
if s.protocol == "unix" && s.address[0] != '@' {
os.Remove(s.address)
}
var err error
l, err = listen(ctx, s.protocol, s.address)
if err != nil {
return err
}
if s.protocol == "unix" && s.address[0] != '@' {
l.(*net.UnixListener).SetUnlinkOnClose(true)
}
}
s.mutex.Lock()
s.listener = l
s.mutex.Unlock()
return nil
}
func (s *Service) refreshTimeout(timeout time.Duration) error {
type setDeadliner interface {
SetDeadline(time.Time) error
}
switch l := s.listener.(type) {
case setDeadliner:
if err := l.SetDeadline(time.Now().Add(timeout)); err != nil {
return err
}
}
return nil
}
// Bind binds the service to an address.
func (s *Service) Bind(ctx context.Context, address string) error {
s.mutex.Lock()
if s.running {
s.mutex.Unlock()
return fmt.Errorf("Init(): already running")
}
s.mutex.Unlock()
s.parseAddress(address)
err := s.setListener(ctx)
if err != nil {
return err
}
return nil
}
// Listen starts a Service.
func (s *Service) Listen(ctx context.Context, address string, timeout time.Duration) error {
var wg sync.WaitGroup
defer func() { s.teardown(); wg.Wait() }()
err := s.Bind(ctx, address)
if err != nil {
return err
}
s.mutex.Lock()
s.running = true
l := s.listener
s.mutex.Unlock()
for s.running {
if timeout != 0 {
if err := s.refreshTimeout(timeout); err != nil {
return err
}
}
conn, err := l.Accept()
if err != nil {
if err.(net.Error).Timeout() {
s.mutex.Lock()
if s.conncounter == 0 {
s.mutex.Unlock()
return ServiceTimeoutError{}
}
s.mutex.Unlock()
continue
}
if !s.running {
return nil
}
return err
}
s.mutex.Lock()
s.conncounter++
s.mutex.Unlock()
wg.Add(1)
go s.handleConnection(ctx, conn, &wg)
}
return nil
}
// DoListen starts a Service.
func (s *Service) DoListen(ctx context.Context, timeout time.Duration) error {
var wg sync.WaitGroup
defer func() { s.teardown(); wg.Wait() }()
s.mutex.Lock()
l := s.listener
s.mutex.Unlock()
if l == nil {
return fmt.Errorf("No listener set")
}
s.mutex.Lock()
s.running = true
s.mutex.Unlock()
for s.running {
if timeout != 0 {
if err := s.refreshTimeout(timeout); err != nil {
return err
}
}
conn, err := l.Accept()
if err != nil {
if err.(net.Error).Timeout() {
s.mutex.Lock()
if s.conncounter == 0 {
s.mutex.Unlock()
return ServiceTimeoutError{}
}
s.mutex.Unlock()
continue
}
if !s.running {
return nil
}
return err
}
s.mutex.Lock()
s.conncounter++
s.mutex.Unlock()
wg.Add(1)
go s.handleConnection(ctx, conn, &wg)
}
return nil
}
// RegisterInterface registers a varlink.Interface containing struct to the Service
func (s *Service) RegisterInterface(iface dispatcher) error {
name := iface.VarlinkGetName()
if _, ok := s.interfaces[name]; ok {
return fmt.Errorf("interface '%s' already registered", name)
}
if s.running {
return fmt.Errorf("service is already running")
}
s.interfaces[name] = iface
s.descriptions[name] = iface.VarlinkGetDescription()
s.names = append(s.names, name)
return nil
}
// NewService creates a new Service which implements the list of given varlink interfaces.
func NewService(vendor string, product string, version string, url string) (*Service, error) {
s := Service{
vendor: vendor,
product: product,
version: version,
url: url,
interfaces: make(map[string]dispatcher),
descriptions: make(map[string]string),
}
err := s.RegisterInterface(orgvarlinkserviceNew())
return &s, err
}
|