]> git.r.bdr.sh - rbdr/mobius/blobdiff - hotline/client.go
Initial refactor to split client from protocol package
[rbdr/mobius] / hotline / client.go
index 493d59e9473af71e53ab1bb8b49300d5141ffd14..6abe62322bfd3c95d6fc99f0b5137190a682edb5 100644 (file)
@@ -1,6 +1,7 @@
 package hotline
 
 import (
+       "bufio"
        "bytes"
        "embed"
        "encoding/binary"
@@ -10,7 +11,7 @@ import (
        "github.com/rivo/tview"
        "github.com/stretchr/testify/mock"
        "go.uber.org/zap"
-       "gopkg.in/yaml.v2"
+       "gopkg.in/yaml.v3"
        "math/big"
        "math/rand"
        "net"
@@ -35,10 +36,11 @@ type Bookmark struct {
 }
 
 type ClientPrefs struct {
-       Username  string     `yaml:"Username"`
-       IconID    int        `yaml:"IconID"`
-       Bookmarks []Bookmark `yaml:"Bookmarks"`
-       Tracker   string     `yaml:"Tracker"`
+       Username   string     `yaml:"Username"`
+       IconID     int        `yaml:"IconID"`
+       Bookmarks  []Bookmark `yaml:"Bookmarks"`
+       Tracker    string     `yaml:"Tracker"`
+       EnableBell bool       `yaml:"EnableBell"`
 }
 
 func (cp *ClientPrefs) IconBytes() []byte {
@@ -61,7 +63,6 @@ func readConfig(cfgPath string) (*ClientPrefs, error) {
 
        prefs := ClientPrefs{}
        decoder := yaml.NewDecoder(fh)
-       decoder.SetStrict(true)
        if err := decoder.Decode(&prefs); err != nil {
                return nil, err
        }
@@ -72,11 +73,6 @@ type Client struct {
        cfgPath     string
        DebugBuf    *DebugBuffer
        Connection  net.Conn
-       Login       *[]byte
-       Password    *[]byte
-       Flags       *[]byte
-       ID          *[]byte
-       Version     []byte
        UserAccess  []byte
        filePath    []string
        UserList    []User
@@ -84,16 +80,27 @@ type Client struct {
        activeTasks map[uint32]*Transaction
        serverName  string
 
-       pref *ClientPrefs
+       Pref *ClientPrefs
 
-       Handlers map[uint16]clientTHandler
+       Handlers map[uint16]ClientTHandler
 
        UI *UI
 
-       Inbox  chan *Transaction
+       Inbox chan *Transaction
 }
 
-func NewClient(cfgPath string, logger *zap.SugaredLogger) *Client {
+func NewClient(username string, logger *zap.SugaredLogger) *Client {
+       c := &Client{
+               Logger:      logger,
+               activeTasks: make(map[uint32]*Transaction),
+               Handlers:    make(map[uint16]ClientTHandler),
+       }
+       c.Pref = &ClientPrefs{Username: username}
+
+       return c
+}
+
+func NewUIClient(cfgPath string, logger *zap.SugaredLogger) *Client {
        c := &Client{
                cfgPath:     cfgPath,
                Logger:      logger,
@@ -104,10 +111,9 @@ func NewClient(cfgPath string, logger *zap.SugaredLogger) *Client {
 
        prefs, err := readConfig(cfgPath)
        if err != nil {
-               fmt.Printf("unable to read config file %s", cfgPath)
-               os.Exit(1)
+               logger.Fatal(fmt.Sprintf("unable to read config file %s\n", cfgPath))
        }
-       c.pref = prefs
+       c.Pref = prefs
 
        return c
 }
@@ -121,7 +127,7 @@ func (db *DebugBuffer) Write(p []byte) (int, error) {
        return db.TextView.Write(p)
 }
 
-// Sync is a noop function that exists to satisfy the zapcore.WriteSyncer interface
+// Sync is a noop function that dataFile to satisfy the zapcore.WriteSyncer interface
 func (db *DebugBuffer) Sync() error {
        return nil
 }
@@ -135,16 +141,16 @@ func randomBanner() string {
        return fmt.Sprintf("\n\n\nWelcome to...\n\n[red::b]%s[-:-:-]\n\n", file)
 }
 
-type clientTransaction struct {
+type ClientTransaction struct {
        Name    string
        Handler func(*Client, *Transaction) ([]Transaction, error)
 }
 
-func (ch clientTransaction) Handle(cc *Client, t *Transaction) ([]Transaction, error) {
+func (ch ClientTransaction) Handle(cc *Client, t *Transaction) ([]Transaction, error) {
        return ch.Handler(cc, t)
 }
 
-type clientTHandler interface {
+type ClientTHandler interface {
        Handle(*Client, *Transaction) ([]Transaction, error)
 }
 
@@ -157,50 +163,50 @@ func (mh *mockClientHandler) Handle(cc *Client, t *Transaction) ([]Transaction,
        return args.Get(0).([]Transaction), args.Error(1)
 }
 
-var clientHandlers = map[uint16]clientTHandler{
+var clientHandlers = map[uint16]ClientTHandler{
        // Server initiated
-       tranChatMsg: clientTransaction{
-               Name:    "tranChatMsg",
+       TranChatMsg: ClientTransaction{
+               Name:    "TranChatMsg",
                Handler: handleClientChatMsg,
        },
-       tranLogin: clientTransaction{
-               Name:    "tranLogin",
+       TranLogin: ClientTransaction{
+               Name:    "TranLogin",
                Handler: handleClientTranLogin,
        },
-       tranShowAgreement: clientTransaction{
-               Name:    "tranShowAgreement",
+       TranShowAgreement: ClientTransaction{
+               Name:    "TranShowAgreement",
                Handler: handleClientTranShowAgreement,
        },
-       tranUserAccess: clientTransaction{
-               Name:    "tranUserAccess",
+       TranUserAccess: ClientTransaction{
+               Name:    "TranUserAccess",
                Handler: handleClientTranUserAccess,
        },
-       tranGetUserNameList: clientTransaction{
-               Name:    "tranGetUserNameList",
+       TranGetUserNameList: ClientTransaction{
+               Name:    "TranGetUserNameList",
                Handler: handleClientGetUserNameList,
        },
-       tranNotifyChangeUser: clientTransaction{
-               Name:    "tranNotifyChangeUser",
+       TranNotifyChangeUser: ClientTransaction{
+               Name:    "TranNotifyChangeUser",
                Handler: handleNotifyChangeUser,
        },
-       tranNotifyDeleteUser: clientTransaction{
-               Name:    "tranNotifyDeleteUser",
+       TranNotifyDeleteUser: ClientTransaction{
+               Name:    "TranNotifyDeleteUser",
                Handler: handleNotifyDeleteUser,
        },
-       tranGetMsgs: clientTransaction{
-               Name:    "tranNotifyDeleteUser",
+       TranGetMsgs: ClientTransaction{
+               Name:    "TranNotifyDeleteUser",
                Handler: handleGetMsgs,
        },
-       tranGetFileNameList: clientTransaction{
-               Name:    "tranGetFileNameList",
+       TranGetFileNameList: ClientTransaction{
+               Name:    "TranGetFileNameList",
                Handler: handleGetFileNameList,
        },
-       tranServerMsg: clientTransaction{
-               Name:    "tranServerMsg",
+       TranServerMsg: ClientTransaction{
+               Name:    "TranServerMsg",
                Handler: handleTranServerMsg,
        },
-       tranKeepAlive: clientTransaction{
-               Name:    "tranKeepAlive",
+       TranKeepAlive: ClientTransaction{
+               Name: "TranKeepAlive",
                Handler: func(client *Client, transaction *Transaction) (t []Transaction, err error) {
                        return t, err
                },
@@ -210,9 +216,9 @@ var clientHandlers = map[uint16]clientTHandler{
 func handleTranServerMsg(c *Client, t *Transaction) (res []Transaction, err error) {
        time := time.Now().Format(time.RFC850)
 
-       msg := strings.ReplaceAll(string(t.GetField(fieldData).Data), "\r", "\n")
+       msg := strings.ReplaceAll(string(t.GetField(FieldData).Data), "\r", "\n")
        msg += "\n\nAt " + time
-       title := fmt.Sprintf("| Private Message From:   %s |", t.GetField(fieldUserName).Data)
+       title := fmt.Sprintf("| Private Message From:   %s |", t.GetField(FieldUserName).Data)
 
        msgBox := tview.NewTextView().SetScrollable(true)
        msgBox.SetText(msg).SetBackgroundColor(tcell.ColorDarkSlateBlue)
@@ -239,7 +245,41 @@ func handleTranServerMsg(c *Client, t *Transaction) (res []Transaction, err erro
        return res, err
 }
 
+func (c *Client) showErrMsg(msg string) {
+       time := time.Now().Format(time.RFC850)
+
+       title := "| Error |"
+
+       msgBox := tview.NewTextView().SetScrollable(true)
+       msgBox.SetText(msg).SetBackgroundColor(tcell.ColorDarkRed)
+       msgBox.SetTitle(title).SetBorder(true)
+       msgBox.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
+               switch event.Key() {
+               case tcell.KeyEscape:
+                       c.UI.Pages.RemovePage("serverMsgModal" + time)
+               }
+               return event
+       })
+
+       centeredFlex := tview.NewFlex().
+               AddItem(nil, 0, 1, false).
+               AddItem(tview.NewFlex().SetDirection(tview.FlexRow).
+                       AddItem(nil, 0, 1, false).
+                       AddItem(msgBox, 0, 2, true).
+                       AddItem(nil, 0, 1, false), 0, 2, true).
+               AddItem(nil, 0, 1, false)
+
+       c.UI.Pages.AddPage("serverMsgModal"+time, centeredFlex, true, true)
+       c.UI.App.Draw() // TODO: errModal doesn't render without this.  wtf?
+}
+
 func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err error) {
+       if t.IsError() {
+               c.showErrMsg(string(t.GetField(FieldError).Data))
+               c.Logger.Infof("Error: %s", t.GetField(FieldError).Data)
+               return res, err
+       }
+
        fTree := tview.NewTreeView().SetTopLevel(1)
        root := tview.NewTreeNode("Root")
        fTree.SetRoot(root).SetCurrentNode(root)
@@ -254,9 +294,9 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er
 
                        if selectedNode.GetText() == "<- Back" {
                                c.filePath = c.filePath[:len(c.filePath)-1]
-                               f := NewField(fieldFilePath, EncodeFilePath(strings.Join(c.filePath, "/")))
+                               f := NewField(FieldFilePath, EncodeFilePath(strings.Join(c.filePath, "/")))
 
-                               if err := c.UI.HLClient.Send(*NewTransaction(tranGetFileNameList, nil, f)); err != nil {
+                               if err := c.UI.HLClient.Send(*NewTransaction(TranGetFileNameList, nil, f)); err != nil {
                                        c.UI.HLClient.Logger.Errorw("err", "err", err)
                                }
                                return event
@@ -264,18 +304,18 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er
 
                        entry := selectedNode.GetReference().(*FileNameWithInfo)
 
-                       if bytes.Equal(entry.Type, []byte("fldr")) {
-                               c.Logger.Infow("get new directory listing", "name", string(entry.Name))
+                       if bytes.Equal(entry.Type[:], []byte("fldr")) {
+                               c.Logger.Infow("get new directory listing", "name", string(entry.name))
 
-                               c.filePath = append(c.filePath, string(entry.Name))
-                               f := NewField(fieldFilePath, EncodeFilePath(strings.Join(c.filePath, "/")))
+                               c.filePath = append(c.filePath, string(entry.name))
+                               f := NewField(FieldFilePath, EncodeFilePath(strings.Join(c.filePath, "/")))
 
-                               if err := c.UI.HLClient.Send(*NewTransaction(tranGetFileNameList, nil, f)); err != nil {
+                               if err := c.UI.HLClient.Send(*NewTransaction(TranGetFileNameList, nil, f)); err != nil {
                                        c.UI.HLClient.Logger.Errorw("err", "err", err)
                                }
                        } else {
                                // TODO: initiate file download
-                               c.Logger.Infow("download file", "name", string(entry.Name))
+                               c.Logger.Infow("download file", "name", string(entry.name))
                        }
                }
 
@@ -289,16 +329,19 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er
 
        for _, f := range t.Fields {
                var fn FileNameWithInfo
-               _, _ = fn.Read(f.Data)
+               err = fn.UnmarshalBinary(f.Data)
+               if err != nil {
+                       return nil, nil
+               }
 
-               if bytes.Equal(fn.Type, []byte("fldr")) {
-                       node := tview.NewTreeNode(fmt.Sprintf("[blue::]📁 %s[-:-:-]", fn.Name))
+               if bytes.Equal(fn.Type[:], []byte("fldr")) {
+                       node := tview.NewTreeNode(fmt.Sprintf("[blue::]📁 %s[-:-:-]", fn.name))
                        node.SetReference(&fn)
                        root.AddChild(node)
                } else {
-                       size := binary.BigEndian.Uint32(fn.FileSize) / 1024
+                       size := binary.BigEndian.Uint32(fn.FileSize[:]) / 1024
 
-                       node := tview.NewTreeNode(fmt.Sprintf("   %-40s %10v KB", fn.Name, size))
+                       node := tview.NewTreeNode(fmt.Sprintf("   %-40s %10v KB", fn.name, size))
                        node.SetReference(&fn)
                        root.AddChild(node)
                }
@@ -321,7 +364,7 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er
 }
 
 func handleGetMsgs(c *Client, t *Transaction) (res []Transaction, err error) {
-       newsText := string(t.GetField(fieldData).Data)
+       newsText := string(t.GetField(FieldData).Data)
        newsText = strings.ReplaceAll(newsText, "\r", "\n")
 
        newsTextView := tview.NewTextView().
@@ -333,8 +376,8 @@ func handleGetMsgs(c *Client, t *Transaction) (res []Transaction, err error) {
        newsTextView.SetBorder(true).SetTitle("News")
 
        c.UI.Pages.AddPage("news", newsTextView, true, true)
-       //c.UI.Pages.SwitchToPage("news")
-       //c.UI.App.SetFocus(newsTextView)
+       // c.UI.Pages.SwitchToPage("news")
+       // c.UI.App.SetFocus(newsTextView)
        c.UI.App.Draw()
 
        return res, err
@@ -342,10 +385,10 @@ func handleGetMsgs(c *Client, t *Transaction) (res []Transaction, err error) {
 
 func handleNotifyChangeUser(c *Client, t *Transaction) (res []Transaction, err error) {
        newUser := User{
-               ID:    t.GetField(fieldUserID).Data,
-               Name:  string(t.GetField(fieldUserName).Data),
-               Icon:  t.GetField(fieldUserIconID).Data,
-               Flags: t.GetField(fieldUserFlags).Data,
+               ID:    t.GetField(FieldUserID).Data,
+               Name:  string(t.GetField(FieldUserName).Data),
+               Icon:  t.GetField(FieldUserIconID).Data,
+               Flags: t.GetField(FieldUserFlags).Data,
        }
 
        // Possible cases:
@@ -380,7 +423,7 @@ func handleNotifyChangeUser(c *Client, t *Transaction) (res []Transaction, err e
 }
 
 func handleNotifyDeleteUser(c *Client, t *Transaction) (res []Transaction, err error) {
-       exitUser := t.GetField(fieldUserID).Data
+       exitUser := t.GetField(FieldUserID).Data
 
        var newUserList []User
        for _, u := range c.UserList {
@@ -396,59 +439,11 @@ func handleNotifyDeleteUser(c *Client, t *Transaction) (res []Transaction, err e
        return res, err
 }
 
-const readBuffSize = 1024000 // 1KB - TODO: what should this be?
-
-func (c *Client) ReadLoop() error {
-       tranBuff := make([]byte, 0)
-       tReadlen := 0
-       // Infinite loop where take action on incoming client requests until the connection is closed
-       for {
-               buf := make([]byte, readBuffSize)
-               tranBuff = tranBuff[tReadlen:]
-
-               readLen, err := c.Connection.Read(buf)
-               if err != nil {
-                       return err
-               }
-               tranBuff = append(tranBuff, buf[:readLen]...)
-
-               // We may have read multiple requests worth of bytes from Connection.Read.  readTransactions splits them
-               // into a slice of transactions
-               var transactions []Transaction
-               if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
-                       c.Logger.Errorw("Error handling transaction", "err", err)
-               }
-
-               // iterate over all of the transactions that were parsed from the byte slice and handle them
-               for _, t := range transactions {
-                       if err := c.HandleTransaction(&t); err != nil {
-                               c.Logger.Errorw("Error handling transaction", "err", err)
-                       }
-               }
-       }
-}
-
-func (c *Client) GetTransactions() error {
-       tranBuff := make([]byte, 0)
-       tReadlen := 0
-
-       buf := make([]byte, readBuffSize)
-       tranBuff = tranBuff[tReadlen:]
-
-       readLen, err := c.Connection.Read(buf)
-       if err != nil {
-               return err
-       }
-       tranBuff = append(tranBuff, buf[:readLen]...)
-
-       return nil
-}
-
 func handleClientGetUserNameList(c *Client, t *Transaction) (res []Transaction, err error) {
        var users []User
        for _, field := range t.Fields {
-               // The Hotline protocol docs say that ClientGetUserNameList should only return fieldUsernameWithInfo (300)
-               // fields, but shxd sneaks in fieldChatSubject (115) so it's important to filter explicitly for the expected
+               // The Hotline protocol docs say that ClientGetUserNameList should only return FieldUsernameWithInfo (300)
+               // fields, but shxd sneaks in FieldChatSubject (115) so it's important to filter explicitly for the expected
                // field type.  Probably a good idea to do everywhere.
                if bytes.Equal(field.ID, []byte{0x01, 0x2c}) {
                        u, err := ReadUser(field.Data)
@@ -479,33 +474,37 @@ func (c *Client) renderUserList() {
 }
 
 func handleClientChatMsg(c *Client, t *Transaction) (res []Transaction, err error) {
-       _, _ = fmt.Fprintf(c.UI.chatBox, "%s \n", t.GetField(fieldData).Data)
+       if c.Pref.EnableBell {
+               fmt.Println("\a")
+       }
+
+       _, _ = fmt.Fprintf(c.UI.chatBox, "%s \n", t.GetField(FieldData).Data)
 
        return res, err
 }
 
 func handleClientTranUserAccess(c *Client, t *Transaction) (res []Transaction, err error) {
-       c.UserAccess = t.GetField(fieldUserAccess).Data
+       c.UserAccess = t.GetField(FieldUserAccess).Data
 
        return res, err
 }
 
 func handleClientTranShowAgreement(c *Client, t *Transaction) (res []Transaction, err error) {
-       agreement := string(t.GetField(fieldData).Data)
+       agreement := string(t.GetField(FieldData).Data)
        agreement = strings.ReplaceAll(agreement, "\r", "\n")
 
-       c.UI.agreeModal = tview.NewModal().
+       agreeModal := tview.NewModal().
                SetText(agreement).
                AddButtons([]string{"Agree", "Disagree"}).
                SetDoneFunc(func(buttonIndex int, buttonLabel string) {
                        if buttonIndex == 0 {
                                res = append(res,
                                        *NewTransaction(
-                                               tranAgreed, nil,
-                                               NewField(fieldUserName, []byte(c.pref.Username)),
-                                               NewField(fieldUserIconID, c.pref.IconBytes()),
-                                               NewField(fieldUserFlags, []byte{0x00, 0x00}),
-                                               NewField(fieldOptions, []byte{0x00, 0x00}),
+                                               TranAgreed, nil,
+                                               NewField(FieldUserName, []byte(c.Pref.Username)),
+                                               NewField(FieldUserIconID, c.Pref.IconBytes()),
+                                               NewField(FieldUserFlags, []byte{0x00, 0x00}),
+                                               NewField(FieldOptions, []byte{0x00, 0x00}),
                                        ),
                                )
                                c.UI.Pages.HidePage("agreement")
@@ -517,17 +516,14 @@ func handleClientTranShowAgreement(c *Client, t *Transaction) (res []Transaction
                },
                )
 
-       c.Logger.Debug("show agreement page")
-       c.UI.Pages.AddPage("agreement", c.UI.agreeModal, false, true)
-       c.UI.Pages.ShowPage("agreement ")
-       c.UI.App.Draw()
+       c.UI.Pages.AddPage("agreement", agreeModal, false, true)
 
        return res, err
 }
 
 func handleClientTranLogin(c *Client, t *Transaction) (res []Transaction, err error) {
        if !bytes.Equal(t.ErrorCode, []byte{0, 0, 0, 0}) {
-               errMsg := string(t.GetField(fieldError).Data)
+               errMsg := string(t.GetField(FieldError).Data)
                errModal := tview.NewModal()
                errModal.SetText(errMsg)
                errModal.AddButtons([]string{"Oh no"})
@@ -539,22 +535,23 @@ func handleClientTranLogin(c *Client, t *Transaction) (res []Transaction, err er
 
                c.UI.App.Draw() // TODO: errModal doesn't render without this.  wtf?
 
-               c.Logger.Error(string(t.GetField(fieldError).Data))
-               return nil, errors.New("login error: " + string(t.GetField(fieldError).Data))
+               c.Logger.Error(string(t.GetField(FieldError).Data))
+               return nil, errors.New("login error: " + string(t.GetField(FieldError).Data))
        }
        c.UI.Pages.AddAndSwitchToPage(serverUIPage, c.UI.renderServerUI(), true)
        c.UI.App.SetFocus(c.UI.chatInput)
 
-       if err := c.Send(*NewTransaction(tranGetUserNameList, nil)); err != nil {
+       if err := c.Send(*NewTransaction(TranGetUserNameList, nil)); err != nil {
                c.Logger.Errorw("err", "err", err)
        }
        return res, err
 }
 
 // JoinServer connects to a Hotline server and completes the login flow
-func (c *Client) JoinServer(address, login, passwd string) error {
+func (c *Client) Connect(address, login, passwd string) (err error) {
        // Establish TCP connection to server
-       if err := c.connect(address); err != nil {
+       c.Connection, err = net.DialTimeout("tcp", address, 5*time.Second)
+       if err != nil {
                return err
        }
 
@@ -563,7 +560,7 @@ func (c *Client) JoinServer(address, login, passwd string) error {
                return err
        }
 
-       // Authenticate (send tranLogin 107)
+       // Authenticate (send TranLogin 107)
        if err := c.LogIn(login, passwd); err != nil {
                return err
        }
@@ -577,21 +574,11 @@ func (c *Client) JoinServer(address, login, passwd string) error {
 func (c *Client) keepalive() error {
        for {
                time.Sleep(300 * time.Second)
-               _ = c.Send(*NewTransaction(tranKeepAlive, nil))
+               _ = c.Send(*NewTransaction(TranKeepAlive, nil))
                c.Logger.Infow("Sent keepalive ping")
        }
 }
 
-// connect establishes a connection with a Server by sending handshake sequence
-func (c *Client) connect(address string) error {
-       var err error
-       c.Connection, err = net.DialTimeout("tcp", address, 5*time.Second)
-       if err != nil {
-               return err
-       }
-       return nil
-}
-
 var ClientHandshake = []byte{
        0x54, 0x52, 0x54, 0x50, // TRTP
        0x48, 0x4f, 0x54, 0x4c, // HOTL
@@ -605,10 +592,10 @@ var ServerHandshake = []byte{
 }
 
 func (c *Client) Handshake() error {
-       //Protocol ID   4       ‘TRTP’      0x54 52 54 50
-       //Sub-protocol ID       4               User defined
-       //Version       2       1       Currently 1
-       //Sub-version   2               User defined
+       // Protocol ID  4       ‘TRTP’      0x54 52 54 50
+       // Sub-protocol ID      4               User defined
+       // Version      2       1       Currently 1
+       // Sub-version  2               User defined
        if _, err := c.Connection.Write(ClientHandshake); err != nil {
                return fmt.Errorf("handshake write err: %s", err)
        }
@@ -619,7 +606,7 @@ func (c *Client) Handshake() error {
                return err
        }
 
-       if bytes.Compare(replyBuf, ServerHandshake) == 0 {
+       if bytes.Equal(replyBuf, ServerHandshake) {
                return nil
        }
 
@@ -630,12 +617,11 @@ func (c *Client) Handshake() error {
 func (c *Client) LogIn(login string, password string) error {
        return c.Send(
                *NewTransaction(
-                       tranLogin, nil,
-                       NewField(fieldUserName, []byte(c.pref.Username)),
-                       NewField(fieldUserIconID, c.pref.IconBytes()),
-                       NewField(fieldUserLogin, negateString([]byte(login))),
-                       NewField(fieldUserPassword, negateString([]byte(password))),
-                       NewField(fieldVersion, []byte{0, 2}),
+                       TranLogin, nil,
+                       NewField(FieldUserName, []byte(c.Pref.Username)),
+                       NewField(FieldUserIconID, c.Pref.IconBytes()),
+                       NewField(FieldUserLogin, negateString([]byte(login))),
+                       NewField(FieldUserPassword, negateString([]byte(password))),
                ),
        )
 }
@@ -644,7 +630,7 @@ func (c *Client) Send(t Transaction) error {
        requestNum := binary.BigEndian.Uint16(t.Type)
        tID := binary.BigEndian.Uint32(t.ID)
 
-       //handler := TransactionHandlers[requestNum]
+       // handler := TransactionHandlers[requestNum]
 
        // if transaction is NOT reply, add it to the list to transactions we're expecting a response for
        if t.IsReply == 0 {
@@ -653,7 +639,11 @@ func (c *Client) Send(t Transaction) error {
 
        var n int
        var err error
-       if n, err = c.Connection.Write(t.Payload()); err != nil {
+       b, err := t.MarshalBinary()
+       if err != nil {
+               return err
+       }
+       if n, err = c.Connection.Write(b); err != nil {
                return err
        }
        c.Logger.Debugw("Sent Transaction",
@@ -673,10 +663,7 @@ func (c *Client) HandleTransaction(t *Transaction) error {
        }
 
        requestNum := binary.BigEndian.Uint16(t.Type)
-       c.Logger.Infow(
-               "Received Transaction",
-               "RequestType", requestNum,
-       )
+       c.Logger.Debugw("Received Transaction", "RequestType", requestNum)
 
        if handler, ok := c.Handlers[requestNum]; ok {
                outT, _ := handler.Handle(c, t)
@@ -684,7 +671,7 @@ func (c *Client) HandleTransaction(t *Transaction) error {
                        c.Send(t)
                }
        } else {
-               c.Logger.Errorw(
+               c.Logger.Debugw(
                        "Unimplemented transaction type received",
                        "RequestID", requestNum,
                        "TransactionID", t.ID,
@@ -694,18 +681,34 @@ func (c *Client) HandleTransaction(t *Transaction) error {
        return nil
 }
 
-func (c *Client) Connected() bool {
-       // c.Agreed == true &&
-       if c.UserAccess != nil {
-               return true
-       }
-       return false
+func (c *Client) Disconnect() error {
+       return c.Connection.Close()
 }
 
-func (c *Client) Disconnect() error {
-       err := c.Connection.Close()
-       if err != nil {
-               return err
+func (c *Client) HandleTransactions() error {
+       // Create a new scanner for parsing incoming bytes into transaction tokens
+       scanner := bufio.NewScanner(c.Connection)
+       scanner.Split(transactionScanner)
+
+       // Scan for new transactions and handle them as they come in.
+       for scanner.Scan() {
+               // Make a new []byte slice and copy the scanner bytes to it.  This is critical to avoid a data race as the
+               // scanner re-uses the buffer for subsequent scans.
+               buf := make([]byte, len(scanner.Bytes()))
+               copy(buf, scanner.Bytes())
+
+               var t Transaction
+               _, err := t.Write(buf)
+               if err != nil {
+                       break
+               }
+               if err := c.HandleTransaction(&t); err != nil {
+                       c.Logger.Errorw("Error handling transaction", "err", err)
+               }
+       }
+
+       if scanner.Err() == nil {
+               return scanner.Err()
        }
        return nil
 }