2021-12-16 19:45:32 -05:00
|
|
|
package oscar
|
2021-11-16 16:44:29 -05:00
|
|
|
|
|
|
|
import (
|
2021-12-17 19:01:22 -05:00
|
|
|
"aim-oscar/util"
|
2021-11-24 11:59:53 -05:00
|
|
|
"context"
|
2021-11-16 16:44:29 -05:00
|
|
|
"fmt"
|
|
|
|
"net"
|
2021-12-15 19:55:43 -05:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2021-11-16 16:44:29 -05:00
|
|
|
)
|
|
|
|
|
2021-11-24 11:59:53 -05:00
|
|
|
type sessionKey string
|
|
|
|
|
|
|
|
func (s sessionKey) String() string {
|
|
|
|
return "oscar-" + string(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
currentSession = sessionKey("session")
|
|
|
|
)
|
|
|
|
|
2021-11-16 16:44:29 -05:00
|
|
|
type Session struct {
|
2021-12-18 16:48:13 -05:00
|
|
|
conn net.Conn
|
2021-11-16 16:44:29 -05:00
|
|
|
SequenceNumber uint16
|
|
|
|
GreetedClient bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSession(conn net.Conn) *Session {
|
|
|
|
return &Session{
|
2021-12-18 16:48:13 -05:00
|
|
|
conn: conn,
|
2021-11-16 16:44:29 -05:00
|
|
|
SequenceNumber: 0,
|
|
|
|
GreetedClient: false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-24 11:59:53 -05:00
|
|
|
func NewContextWithSession(ctx context.Context, conn net.Conn) context.Context {
|
|
|
|
session := NewSession(conn)
|
|
|
|
return context.WithValue(ctx, currentSession, session)
|
|
|
|
}
|
|
|
|
|
2021-12-18 16:48:13 -05:00
|
|
|
func SessionFromContext(ctx context.Context) (session *Session, err error) {
|
2021-12-15 19:55:43 -05:00
|
|
|
s := ctx.Value(currentSession)
|
|
|
|
if s == nil {
|
|
|
|
return nil, errors.New("no session in context")
|
2021-11-24 11:59:53 -05:00
|
|
|
}
|
2021-12-15 19:55:43 -05:00
|
|
|
return s.(*Session), nil
|
2021-11-24 11:59:53 -05:00
|
|
|
}
|
|
|
|
|
2021-12-18 16:48:13 -05:00
|
|
|
func (s *Session) RemoteAddr() net.Addr {
|
|
|
|
return s.conn.RemoteAddr()
|
|
|
|
}
|
|
|
|
|
2021-12-16 18:37:27 -05:00
|
|
|
func (s *Session) Send(flap *FLAP) error {
|
|
|
|
s.SequenceNumber += 1
|
|
|
|
flap.Header.SequenceNumber = s.SequenceNumber
|
|
|
|
bytes, err := flap.MarshalBinary()
|
2021-11-16 16:44:29 -05:00
|
|
|
if err != nil {
|
2021-12-15 19:55:43 -05:00
|
|
|
return errors.Wrap(err, "could not marshal message")
|
2021-11-16 16:44:29 -05:00
|
|
|
}
|
|
|
|
|
2021-12-18 16:48:13 -05:00
|
|
|
fmt.Printf("-> %v\n%s\n\n", s.conn.RemoteAddr(), util.PrettyBytes(bytes))
|
|
|
|
_, err = s.conn.Write(bytes)
|
2021-12-15 19:55:43 -05:00
|
|
|
return errors.Wrap(err, "could not write to client connection")
|
2021-11-16 16:44:29 -05:00
|
|
|
}
|
2021-12-18 16:48:13 -05:00
|
|
|
|
|
|
|
func (s *Session) Disconnect() error {
|
|
|
|
return s.conn.Close()
|
|
|
|
}
|