forked from andrewclausen/otrcat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
99 lines (86 loc) · 2.11 KB
/
message.go
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
// Copyright (C) 2014 Andrew Clausen
// This program may be distributed under the BSD-style licence that Go is
// released under; see https://golang.org/LICENSE.
//
// The OTR protocol is designed to work with instant messenger protocols, in
// which messages are delivered one-by-one. However, otrcat uses TCP to
// deliver messages, which combines and splits packets in an ad hoc way. Our
// solution is to delimit messages using new-lines. Newlines are unobtrusive,
// (especially since OTR messages are base64-sendd), so this shouldn't cause
// compatibility problems.
package main
import (
"bytes"
"errors"
"io"
)
type MessageSender interface {
Send([]byte) error
}
type MessageReceiver interface {
Receive() ([]byte, error)
}
type DelimitedSender struct {
Writer io.Writer
delimiter []byte
}
type DelimitedReceiver struct {
Reader io.Reader
delimiter []byte
queue []byte
}
func NewDelimitedSender(writer io.Writer, delimiter []byte) *DelimitedSender {
return &DelimitedSender{writer, delimiter}
}
func NewDelimitedReceiver(reader io.Reader, delimiter []byte) *DelimitedReceiver {
return &DelimitedReceiver{reader, delimiter, []byte{}}
}
func (s *DelimitedSender) Send(data []byte) (err error) {
_, err = s.Writer.Write(append(data, s.delimiter...))
return
}
func (r *DelimitedReceiver) Receive() (buf []byte, err error) {
var k, n int
for {
n = bytes.Index(r.queue, r.delimiter)
if n != -1 {
break
}
input := make([]byte, 4096)
k, err = r.Reader.Read(input)
if err != nil {
if err == io.EOF && len(r.queue) > 0 {
return nil, errors.New("Stream closed mid-message")
}
return
}
r.queue = append(r.queue, input[:k]...)
}
m := n + len(r.delimiter)
buf, r.queue = r.queue[:n], r.queue[m:]
return
}
func SendForever(s MessageSender, ch chan []byte) {
for {
msg, open := <-ch
if !open || msg == nil {
return
}
if err := s.Send(msg); err != nil {
exitError(err)
}
}
}
func ReceiveForever(r MessageReceiver, ch chan []byte) {
for {
buf, err := r.Receive()
if err == io.EOF {
close(ch)
return
}
if err != nil {
exitError(err)
}
ch <- buf
}
}