summaryrefslogtreecommitdiff
path: root/src/globster/hub/hub.go
blob: 6ee62371f88605dafd56947d5270dbf95a325b3e (plain)
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
package hub

import (
	"blicky.net/asyncwr"
	"blicky.net/tanja"
	"errors"
	"globster/adc"
	"net"
	"time"
)

type hub struct {
	name string
	ses  *tanja.Session
	// Only set in the connected state, nil otherwise.
	conn net.Conn
	wr   *adc.Writer
	rd   <-chan *adc.Message
	// Channel for the asynchronous connect. Only set in the connecting state,
	// otherwise nil. Only one value is written to the channel, a net.Conn on
	// success or an error otherwise.
	connCh <-chan interface{}
	// ADC info (only useful if conn != nil)
	state adc.State
	mysid string
}

func newHub(node *tanja.Node, name string) *hub {
	s := &hub{name: name, ses: node.Session()}

	s.ses.RegRPC(s, func(s string) tanja.Tuple {
		if s[0] != 'T' {
			return nil
		}
		return tanja.Tup("hub", name, s[1:])
	})

	s.ses.Send(false, "hub", name, "Created")

	go func() {
		for {
			select {
			case m, ok := <-s.ses.Chan():
				if !ok {
					return
				}
				m.Dispatch()
			case m := <-s.rd:
				if m == nil {
					s.rd = nil
				} else if err := adc.HandleHub(m, s.state, s); err != nil {
					s.ses.Send(false, "hub", s.name, "disconnect", err.Error())
				}
			case c := <-s.connCh:
				s.connected(c)
			}
		}
		s.ses.Run()
	}()
	return s
}

func (s *hub) Texists(m *tanja.Message) {
	m.Reply(s.name)
	m.Close()
}

func (s *hub) Tconnect(addr string) {
	if s.conn != nil || s.connCh != nil {
		return
	}
	ch := make(chan interface{}, 2)
	s.connCh = ch
	go func() {
		c, e := net.DialTimeout("tcp", addr, 30*time.Second)
		if e != nil {
			ch <- e
		} else {
			ch <- c
		}
	}()
}

// Sending 'disconnect' will immediately put the hub into disconnected state,
// but the actual disconnect from the hub may take a while. The "Disconnected"
// notification is sent immediately, but the return path is only closed after
// the disconnect has been completed.
func (s *hub) Tdisconnect(m *tanja.Message, r ...tanja.Element) {
	broadcast := false

	if s.connCh != nil {
		broadcast = true
		// If we're in the connecting state, set connCh to nil so we won't be
		// getting its result. In case the connection was successful, make sure
		// to immediately disconnect again.
		go func(ch <-chan interface{}) {
			if c, ok := (<-ch).(net.Conn); ok {
				c.Close()
			}
		}(s.connCh)
		s.connCh = nil
		m.Close()

	} else if s.conn != nil {
		broadcast = true
		// If we're connected, close the connection.
		go func(c net.Conn) {
			c.Close()
			m.Close()
		}(s.conn)
		s.conn = nil
		s.wr = nil
		// Also drain the reader channel (to make sure the reader goroutine doesn't deadlock)
		if s.rd != nil {
			go func(ch <-chan *adc.Message) {
				for _ = range ch {
				}
			}(s.rd)
			s.rd = nil
		}

	} else {
		m.Close()
	}

	if broadcast {
		s.ses.Sendt(false, append(tanja.Tup("hub", s.name, "Disconnected"), r...))
	}
}

func (s *hub) connected(r interface{}) {
	s.connCh = nil
	if e, ok := r.(error); ok {
		s.ses.Send(false, "hub", s.name, "Disconnected", e.Error())
		return
	}

	// Successful connect
	s.conn = r.(net.Conn)
	s.ses.Send(false, "hub", s.name, "Connected", s.conn.RemoteAddr().String())
	s.wr = adc.NewWriter(asyncwr.New(s.conn, 1024*1024))

	// Start reader goroutine
	ch := make(chan *adc.Message, 10)
	s.rd = ch
	go func(rd *adc.Reader) {
		for {
			m, err := rd.Read()
			if err != nil {
				s.ses.Send(false, "hub", s.name, "disconnect", err.Error())
				break
			} else if m != nil {
				ch <- m
			}
		}
		close(ch)
	}(adc.NewReader(s.conn, 100*1024))

	// Initiate handshake
	s.state = adc.PROTOCOL
	s.wr.Write(adc.NewMessage('H', adc.SUP).AddNamed("AD", "BASE").AddNamed("AD", "TIGR"))
}

func (s *hub) AdcSUP(ad []string, rm []string) error {
	if s.state != adc.PROTOCOL || len(rm) > 0 {
		return errors.New("Dynamic changing of protocol features is not supported")
	}
	hasbase, hastigr := false, false
	for _, v := range ad {
		if string(v) == "BASE" {
			hasbase = true
		} else if string(v) == "TIGR" {
			hastigr = true
		}
	}
	if !hasbase || !hastigr {
		return errors.New("Hub does not support BASE or TIGR")
	}
	return nil
}

func (s *hub) AdcSID(sid string) error {
	s.mysid = sid
	s.state = adc.IDENTIFY
	return nil
}

func (s *hub) close() {
	r := s.ses.Send(true, "hub", s.name, "disconnect")
	<-r.Chan()
	r.Close()

	s.ses.Close()
	s.ses.Send(false, "hub", s.name, "Closed")
}