Debian Codegraph @

go/pkg/electron/connection.go

raw
1 /*
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements. See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership. The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License. You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing,
13 software distributed under the License is distributed on an
14 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 KIND, either express or implied. See the License for the
16 specific language governing permissions and limitations
17 under the License.
18 */
19
20 package electron
21
22 // #include <proton/disposition.h>
23 import "C"
24
25 import (
26 "crypto/rand"
27 "encoding/hex"
28 "fmt"
29 "net"
30 "sync"
31 "time"
32
33 "github.com/apache/qpid-proton/go/pkg/amqp"
34 "github.com/apache/qpid-proton/go/pkg/proton"
35 )
36
37 // Settings associated with a Connection.
38 type ConnectionSettings interface {
39 // Authenticated user name associated with the connection.
40 User() string
41
42 // The AMQP virtual host name for the connection.
43 //
44 // Optional, useful when the server has multiple names and provides different
45 // service based on the name the client uses to connect.
46 //
47 // By default it is set to the DNS host name that the client uses to connect,
48 // but it can be set to something different at the client side with the
49 // VirtualHost() option.
50 //
51 // Returns error if the connection fails to authenticate.
52 VirtualHost() string
53
54 // Heartbeat is the maximum delay between sending frames that the remote peer
55 // has requested of us. If the interval expires an empty "heartbeat" frame
56 // will be sent automatically to keep the connection open.
57 Heartbeat() time.Duration
58 }
59
60 // Connection is an AMQP connection, created by a Container.
61 type Connection interface {
62 Endpoint
63 ConnectionSettings
64
65 // Sender opens a new sender on the DefaultSession.
66 Sender(...LinkOption) (Sender, error)
67
68 // Receiver opens a new Receiver on the DefaultSession().
69 Receiver(...LinkOption) (Receiver, error)
70
71 // DefaultSession() returns a default session for the connection. It is opened
72 // on the first call to DefaultSession and returned on subsequent calls.
73 DefaultSession() (Session, error)
74
75 // Session opens a new session.
76 Session(...SessionOption) (Session, error)
77
78 // Container for the connection.
79 Container() Container
80
81 // Disconnect the connection abruptly with an error.
82 Disconnect(error)
83
84 // Wait waits for the connection to be disconnected.
85 Wait() error
86
87 // WaitTimeout is like Wait but returns Timeout if the timeout expires.
88 WaitTimeout(time.Duration) error
89
90 // Incoming returns a channel for incoming endpoints opened by the remote peer.
91 // See the Incoming interface for more detail.
92 //
93 // Note: this channel will first return an *IncomingConnection for the
94 // connection itself which allows you to look at security information and
95 // decide whether to Accept() or Reject() the connection. Then it will return
96 // *IncomingSession, *IncomingSender and *IncomingReceiver as they are opened
97 // by the remote end.
98 //
99 // Note 2: you must receiving from Incoming() and call Accept/Reject to avoid
100 // blocking electron event loop. Normally you would run a loop in a goroutine
101 // to handle incoming types that interest and Accept() those that don't.
102 Incoming() <-chan Incoming
103 }
104
105 type connectionSettings struct {
106 user, virtualHost string
107 heartbeat time.Duration
108 }
109
110 func (c connectionSettings) User() string { return c.user }
111 func (c connectionSettings) VirtualHost() string { return c.virtualHost }
112 func (c connectionSettings) Heartbeat() time.Duration { return c.heartbeat }
113
114 // ConnectionOption arguments can be passed when creating a connection to configure it.
115 type ConnectionOption func(*connection)
116
117 // User returns a ConnectionOption sets the user name for a connection
118 func User(user string) ConnectionOption {
119 return func(c *connection) {
120 c.user = user
121 c.pConnection.SetUser(user)
122 }
123 }
124
125 // VirtualHost returns a ConnectionOption to set the AMQP virtual host for the connection.
126 // Only applies to outbound client connection.
127 func VirtualHost(virtualHost string) ConnectionOption {
128 return func(c *connection) {
129 c.virtualHost = virtualHost
130 c.pConnection.SetHostname(virtualHost)
131 }
132 }
133
134 // Password returns a ConnectionOption to set the password used to establish a
135 // connection. Only applies to outbound client connection.
136 //
137 // The connection will erase its copy of the password from memory as soon as it
138 // has been used to authenticate. If you are concerned about passwords staying in
139 // memory you should never store them as strings, and should overwrite your
140 // copy as soon as you are done with it.
141 //
142 func Password(password []byte) ConnectionOption {
143 return func(c *connection) { c.pConnection.SetPassword(password) }
144 }
145
146 // Server returns a ConnectionOption to put the connection in server mode for incoming connections.
147 //
148 // A server connection will do protocol negotiation to accept a incoming AMQP
149 // connection. Normally you would call this for a connection created by
150 // net.Listener.Accept()
151 //
152 func Server() ConnectionOption {
153 return func(c *connection) { c.setServer() }
154 }
155
156 // AllowIncoming returns a ConnectionOption to enable incoming endpoints, see
157 // Connection.Incoming() This is automatically set for Server() connections.
158 func AllowIncoming() ConnectionOption {
159 return func(c *connection) { c.incoming = make(chan Incoming) }
160 }
161
162 // Parent returns a ConnectionOption that associates the Connection with it's Container
163 // If not set a connection will create its own default container.
164 func Parent(cont Container) ConnectionOption {
165 return func(c *connection) { c.container = cont.(*container) }
166 }
167
168 // ContainerId returns a ConnectionOption that creates a new Container
169 // with id and associates it with the connection
170 func ContainerId(id string) ConnectionOption {
171 return func(c *connection) { c.container = NewContainer(id).(*container) }
172 }
173
174 type connection struct {
175 endpoint
176 connectionSettings
177
178 defaultSessionOnce, closeOnce sync.Once
179
180 container *container
181 conn net.Conn
182 server, client bool
183 incoming chan Incoming
184 handler *handler
185 engine *proton.Engine
186 pConnection proton.Connection
187 mc amqp.MessageCodec
188
189 defaultSession Session
190 }
191
192 // NewConnection creates a connection with the given options.
193 // Options are applied in order.
194 func NewConnection(conn net.Conn, opts ...ConnectionOption) (*connection, error) {
195 c := &connection{
196 conn: conn,
197 }
198 c.handler = newHandler(c)
199 var err error
200 c.engine, err = proton.NewEngine(c.conn, c.handler.delegator)
201 if err != nil {
202 return nil, err
203 }
204 c.pConnection = c.engine.Connection()
205 for _, opt := range opts {
206 opt(c)
207 // If the first option is not Server(), then we are a client.
208 // Applying Server() after other options is an error
209 if !c.server {
210 c.client = true
211 }
212 }
213 if c.container == nil {
214 // Generate a random container-id. Not an RFC4122-compliant UUID but probably-unique
215 id := make([]byte, 16)
216 if _, err = rand.Read(id); err != nil {
217 return nil, err
218 }
219 c.container = NewContainer(hex.EncodeToString(id)).(*container)
220 }
221 c.pConnection.SetContainer(c.container.Id())
222 saslConfig.setup(c.engine)
223 c.endpoint.init(c.engine.String())
224 go c.run()
225 return c, nil
226 }
227
228 func (c *connection) setServer() {
229 if c.client {
230 panic("electron.Server() must be first in the ConnectionOption list")
231 }
232 c.server = true
233 c.engine.Server()
234 AllowIncoming()(c)
235 }
236
237 func (c *connection) run() {
238 if !c.server {
239 c.pConnection.Open()
240 }
241 _ = c.engine.Run()
242 if c.incoming != nil {
243 close(c.incoming)
244 }
245 _ = c.closed(Closed)
246 }
247
248 func (c *connection) Close(err error) {
249 c.closeOnce.Do(func() {
250 c.err.Set(err)
251 c.engine.Close(err)
252 c.mc.Close()
253 })
254
255 }
256
257 func (c *connection) Disconnect(err error) {
258 c.err.Set(err)
259 c.engine.Disconnect(err)
260 }
261
262 func (c *connection) Session(opts ...SessionOption) (Session, error) {
263 var s Session
264 err := c.engine.InjectWait(func() error {
265 if c.Error() != nil {
266 return c.Error()
267 }
268 pSession, err := c.engine.Connection().Session()
269 if err == nil {
270 pSession.Open()
271 if err == nil {
272 s = newSession(c, pSession, opts...)
273 }
274 }
275 return err
276 })
277 return s, err
278 }
279
280 func (c *connection) Container() Container { return c.container }
281
282 func (c *connection) DefaultSession() (s Session, err error) {
283 c.defaultSessionOnce.Do(func() {
284 c.defaultSession, err = c.Session()
285 })
286 if err == nil {
287 err = c.Error()
288 }
289 return c.defaultSession, err
290 }
291
292 func (c *connection) Sender(opts ...LinkOption) (Sender, error) {
293 if s, err := c.DefaultSession(); err == nil {
294 return s.Sender(opts...)
295 } else {
296 return nil, err
297 }
298 }
299
300 func (c *connection) Receiver(opts ...LinkOption) (Receiver, error) {
301 if s, err := c.DefaultSession(); err == nil {
302 return s.Receiver(opts...)
303 } else {
304 return nil, err
305 }
306 }
307
308 func (c *connection) Connection() Connection { return c }
309
310 func (c *connection) Wait() error { return c.WaitTimeout(Forever) }
311 func (c *connection) WaitTimeout(timeout time.Duration) error {
312 _, err := timedReceive(c.done, timeout)
313 if err == Timeout {
314 return Timeout
315 }
316 return c.Error()
317 }
318
319 func (c *connection) Incoming() <-chan Incoming {
320 if c.incoming == nil {
321 panic(fmt.Errorf("Incoming() only allowed on Connection created with the Server() option: %s", c))
322 }
323 return c.incoming
324 }
325
326 type IncomingConnection struct {
327 incoming
328 connectionSettings
329 c *connection
330 }
331
332 func newIncomingConnection(c *connection) *IncomingConnection {
333 c.user = c.pConnection.Transport().User()
334 c.virtualHost = c.pConnection.RemoteHostname()
335 c.heartbeat = c.pConnection.Transport().RemoteIdleTimeout()
336 return &IncomingConnection{
337 incoming: makeIncoming(c.pConnection),
338 connectionSettings: c.connectionSettings,
339 c: c}
340 }
341
342 // AcceptConnection is like Accept() but takes ConnectionOption
343 // arguments like NewConnection(). For example you can set the
344 // Heartbeat() for the incoming connection.
345 func (in *IncomingConnection) AcceptConnection(opts ...ConnectionOption) Connection {
346 return in.accept(func() Endpoint {
347 for _, opt := range opts {
348 opt(in.c)
349 }
350 in.c.pConnection.Open()
351 return in.c
352 }).(Connection)
353 }
354
355 func (in *IncomingConnection) Accept() Endpoint {
356 return in.AcceptConnection()
357 }
358
359 func sasl(c *connection) proton.SASL { return c.engine.Transport().SASL() }
360
361 // SASLEnable returns a ConnectionOption that enables SASL authentication.
362 // Only required if you don't set any other SASL options.
363 func SASLEnable() ConnectionOption { return func(c *connection) { sasl(c) } }
364
365 // SASLAllowedMechs returns a ConnectionOption to set the list of allowed SASL
366 // mechanisms.
367 //
368 // Can be used on the client or the server to restrict the SASL for a connection.
369 // mechs is a space-separated list of mechanism names.
370 //
371 // The mechanisms allowed by default are determined by your SASL
372 // library and system configuration, with two exceptions: GSSAPI
373 // and GSS-SPNEGO are disabled by default. To enable them, you
374 // must explicitly add them using this option.
375 //
376 // Clients must set the allowed mechanisms before the the
377 // outgoing connection is attempted. Servers must set them
378 // before the listening connection is setup.
379 //
380 func SASLAllowedMechs(mechs string) ConnectionOption {
381 return func(c *connection) { sasl(c).AllowedMechs(mechs) }
382 }
383
384 // SASLAllowInsecure returns a ConnectionOption that allows or disallows clear
385 // text SASL authentication mechanisms
386 //
387 // By default the SASL layer is configured not to allow mechanisms that disclose
388 // the clear text of the password over an unencrypted AMQP connection. This specifically
389 // will disallow the use of the PLAIN mechanism without using SSL encryption.
390 //
391 // This default is to avoid disclosing password information accidentally over an
392 // insecure network.
393 //
394 func SASLAllowInsecure(b bool) ConnectionOption {
395 return func(c *connection) { sasl(c).SetAllowInsecureMechs(b) }
396 }
397
398 // Heartbeat returns a ConnectionOption that requests the maximum delay
399 // between sending frames for the remote peer. If we don't receive any frames
400 // within 2*delay we will close the connection.
401 //
402 func Heartbeat(delay time.Duration) ConnectionOption {
403 // Proton-C divides the idle-timeout by 2 before sending, so compensate.
404 return func(c *connection) { c.engine.Transport().SetIdleTimeout(2 * delay) }
405 }
406
407 type saslConfigState struct {
408 lock sync.Mutex
409 name string
410 dir string
411 initialized bool
412 }
413
414 func (s *saslConfigState) set(target *string, value string) {
415 s.lock.Lock()
416 defer s.lock.Unlock()
417 if s.initialized {
418 panic("SASL configuration cannot be changed after a Connection has been created")
419 }
420 *target = value
421 }
422
423 // Apply the global SASL configuration the first time a proton.Engine needs it
424 //
425 // TODO aconway 2016-09-15: Current pn_sasl C impl config is broken, so all we
426 // can realistically offer is global configuration. Later if/when the pn_sasl C
427 // impl is fixed we can offer per connection over-rides.
428 func (s *saslConfigState) setup(eng *proton.Engine) {
429 s.lock.Lock()
430 defer s.lock.Unlock()
431 if !s.initialized {
432 s.initialized = true
433 sasl := eng.Transport().SASL()
434 if s.name != "" {
435 sasl.ConfigName(saslConfig.name)
436 }
437 if s.dir != "" {
438 sasl.ConfigPath(saslConfig.dir)
439 }
440 }
441 }
442
443 var saslConfig saslConfigState
444
445 // GlobalSASLConfigDir sets the SASL configuration directory for every
446 // Connection created in this process. If not called, the default is determined
447 // by your SASL installation.
448 //
449 // You can set SASLAllowInsecure and SASLAllowedMechs on individual connections.
450 //
451 // Must be called at most once, before any connections are created.
452 func GlobalSASLConfigDir(dir string) { saslConfig.set(&saslConfig.dir, dir) }
453
454 // GlobalSASLConfigName sets the SASL configuration name for every Connection
455 // created in this process. If not called the default is "proton-server".
456 //
457 // The complete configuration file name is
458 // <sasl-config-dir>/<sasl-config-name>.conf
459 //
460 // You can set SASLAllowInsecure and SASLAllowedMechs on individual connections.
461 //
462 // Must be called at most once, before any connections are created.
463 func GlobalSASLConfigName(name string) { saslConfig.set(&saslConfig.name, name) }
464
465 // Do we support extended SASL negotiation?
466 // All implementations of Proton support ANONYMOUS and EXTERNAL on both
467 // client and server sides and PLAIN on the client side.
468 //
469 // Extended SASL implememtations use an external library (Cyrus SASL)
470 // to support other mechanisms beyond these basic ones.
471 func SASLExtended() bool { return proton.SASLExtended() }
472
473 // Dial is shorthand for using net.Dial() then NewConnection()
474 // See net.Dial() for the meaning of the network, address arguments.
475 func Dial(network, address string, opts ...ConnectionOption) (c Connection, err error) {
476 conn, err := net.Dial(network, address)
477 if err == nil {
478 c, err = NewConnection(conn, opts...)
479 }
480 return
481 }
482
483 // DialWithDialer is shorthand for using dialer.Dial() then NewConnection()
484 // See net.Dial() for the meaning of the network, address arguments.
485 func DialWithDialer(dialer *net.Dialer, network, address string, opts ...ConnectionOption) (c Connection, err error) {
486 conn, err := dialer.Dial(network, address)
487 if err == nil {
488 c, err = NewConnection(conn, opts...)
489 }
490 return
491 }