aim-oscar-server/oscar/server.go

80 lines
1.7 KiB
Go
Raw Normal View History

2021-12-16 19:45:32 -05:00
package oscar
import (
"aim-oscar/util"
"context"
"encoding/binary"
2021-12-16 19:45:32 -05:00
"io"
"log"
"net"
"strings"
2021-12-16 19:45:32 -05:00
"github.com/pkg/errors"
)
type HandlerFunc func(context.Context, *FLAP) context.Context
2021-12-18 17:10:00 -05:00
type HandleCloseFn func(context.Context, *Session)
2021-12-18 17:10:00 -05:00
type Handler struct {
handle HandlerFunc
handleClose HandleCloseFn
}
2021-12-16 19:45:32 -05:00
2021-12-18 17:10:00 -05:00
func NewHandler(fn HandlerFunc, handleClose HandleCloseFn) *Handler {
2021-12-16 19:45:32 -05:00
return &Handler{
2021-12-18 17:10:00 -05:00
handle: fn,
handleClose: handleClose,
2021-12-16 19:45:32 -05:00
}
}
func (h *Handler) Handle(conn net.Conn) {
ctx := NewContextWithSession(context.Background(), conn)
session, _ := SessionFromContext(ctx)
buf := make([]byte, 2048)
2021-12-16 19:45:32 -05:00
for {
if !session.GreetedClient {
// send a hello
hello := NewFLAP(1)
hello.Data.Write([]byte{0, 0, 0, 1})
err := session.Send(hello)
util.PanicIfError(err)
2021-12-16 19:45:32 -05:00
session.GreetedClient = true
}
n, err := conn.Read(buf)
if err != nil && err != io.EOF {
if strings.Contains(err.Error(), "use of closed network connection") {
session.Disconnect()
2021-12-18 17:10:00 -05:00
h.handleClose(ctx, session)
return
}
log.Println("OSCAR Read Error: ", err.Error())
2021-12-16 19:45:32 -05:00
return
}
if n == 0 {
return
}
// Try to parse all of the FLAPs in the buffer if we have enough bytes to
// fill a FLAP header
for len(buf) >= 6 && buf[0] == 0x2a {
dataLength := binary.BigEndian.Uint16(buf[4:6])
2021-12-16 19:45:32 -05:00
flapLength := int(dataLength) + 6
if len(buf) < flapLength {
log.Printf("not enough data, only %d bytes\n", len(buf))
break
}
flap := &FLAP{}
if err := flap.UnmarshalBinary(buf[:flapLength]); err != nil {
util.PanicIfError(errors.Wrap(err, "could not unmarshal FLAP"))
2021-12-16 19:45:32 -05:00
}
buf = buf[flapLength:]
ctx = h.handle(ctx, flap)
2021-12-16 19:45:32 -05:00
}
}
}