mirror of
https://github.com/D-Modem/bbs.git
synced 2026-11-28 17:38:04 -08:00
P3 for an AOL front end: packets and the host's end of a link
internal/aol/p3 is P3, the link layer under the AOL 3.0/4.0 client: - Packets: Append writes them (length, CRC-16/ARC), Reader reads them, passing over what isn't P3, telling a bad CRC or length apart so it can be NAKed, and taking AOL 4.0's "**" in place of a CRC. - Link, started by Serve on a connection: waits for the client's INIT and acknowledges it (byte for byte as hosts that serve live clients do), then DATA in order in and out, tx/rx 0x10-0x7F round the ring, a window of 16, an ACK every 8 DATA or 200ms after a lone one unless a packet of ours carries it, a NAK once for each gap or bad CRC, go-back-N resends on NAK, heartbeats after 12 seconds unacknowledged and the link down after 10, a new INIT starting the link over. - ParseInit reads what the client says of itself; Sniff tells a P3 client's first packet; Token splits a DATA's token from its data. Tested against a client scripted over a pipe (windows, NAKs, resends, heartbeats, wrapping round the sequence numbers), under -race. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B82eRRm1WrfJdB863kw36V
This commit is contained in:
5 files changed
+1352
-4
No files matched your search
@@ -4,7 +4,8 @@ Ideas not yet started, with what is known of them.
|
||||
|
||||
## An AOL front end
|
||||
|
||||
*Status: started; the FDO91 layer (`internal/aol/fdo`) is done.*
|
||||
*Status: started; the FDO91 layer (`internal/aol/fdo`) and P3
|
||||
(`internal/aol/p3`) are done.*
|
||||
|
||||
For AOL 3.0 and 4.0 for Windows, the real clients, over TCP (port 5190, the
|
||||
client's `AmericaOnline.aol.com`) and by modem.
|
||||
@@ -14,9 +15,13 @@ client's `AmericaOnline.aol.com`) and by modem.
|
||||
Ada32.dll byte for byte on AtomForge's corpus (1,889 forms, 74,369
|
||||
single atoms, 44 live captures); a decompiler whose text compiles back
|
||||
to the same bytes.
|
||||
- **P3**, next: the link layer (`5A`, CRC-16, sequence numbers 0x10-0x7F,
|
||||
ACK/NAK, heartbeats, a window of 16), INIT from the client and the
|
||||
host's `SD`; a P3 INIT sniffed on the telnet port hands the caller over.
|
||||
- **P3** (done): packets (CRC-16/ARC, AOL 4.0's `**`), and the host's
|
||||
end of a link: INIT acknowledged, DATA in order in and within a window
|
||||
of 16 out, ACKs every 8 or soon after, NAKs and go-back-N resends,
|
||||
heartbeats after 12 seconds, 10 of them and the link is down.
|
||||
- **Listener**, next: OSCAR's port 5190 already hands a connection that
|
||||
starts with P3's sync byte to `oscar.Server.P3`; serve it there with
|
||||
`p3.Serve`, and sniff a P3 INIT (`p3.Sniff`) on the telnet port too.
|
||||
- **Tokens**: `Dd` sign-on (the form's two `de_data`) to the BBS's login,
|
||||
then chat (`Aa`), IMs (`iS`), mail (`m4`, MIP), keywords (`k1`/`f1`) to
|
||||
areas, `pE` sign-off; each answered with forms compiled from source.
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package p3
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Init is what the client says of itself in its INIT packet: the layout of
|
||||
// the 32-bit Windows client (3.0 and on); other clients' INITs are shorter
|
||||
// or laid out otherwise, and only what they have is filled in.
|
||||
type Init struct {
|
||||
Platform uint8 // 3 Windows, 0x0C Macintosh
|
||||
Version uint8
|
||||
SubVersion uint8
|
||||
MachineMemory uint8
|
||||
AppMemory uint8
|
||||
PCType uint16
|
||||
ReleaseMonth uint8
|
||||
ReleaseDay uint8
|
||||
CustomerClass uint16
|
||||
UDOTimestamp uint32 // when its forms database was made
|
||||
DOSVersion uint16
|
||||
SessionFlags uint16
|
||||
VideoType uint8
|
||||
Processor uint8
|
||||
MediaType uint32
|
||||
WindowsVer uint32
|
||||
MemoryMode uint8
|
||||
Width, Height uint16 // the screen's
|
||||
Colors uint16
|
||||
Region uint16
|
||||
Language [4]uint16
|
||||
ConnectSpeed uint8
|
||||
|
||||
Raw []byte // the INIT's data as it came
|
||||
}
|
||||
|
||||
// The platforms.
|
||||
const (
|
||||
PlatformWindows = 0x03
|
||||
PlatformMac = 0x0C
|
||||
)
|
||||
|
||||
// ParseInit reads an INIT packet's data.
|
||||
func ParseInit(d []byte) Init {
|
||||
in := Init{Raw: append([]byte(nil), d...)}
|
||||
b := make([]byte, 0x31)
|
||||
copy(b, d)
|
||||
be := binary.BigEndian
|
||||
in.Platform, in.Version, in.SubVersion = b[0], b[1], b[2]
|
||||
in.MachineMemory, in.AppMemory = b[4], b[5]
|
||||
in.PCType = be.Uint16(b[6:])
|
||||
in.ReleaseMonth, in.ReleaseDay = b[8], b[9]
|
||||
in.CustomerClass = be.Uint16(b[0x0A:])
|
||||
in.UDOTimestamp = be.Uint32(b[0x0C:])
|
||||
in.DOSVersion = be.Uint16(b[0x10:])
|
||||
in.SessionFlags = be.Uint16(b[0x12:])
|
||||
in.VideoType, in.Processor = b[0x14], b[0x15]
|
||||
in.MediaType = be.Uint32(b[0x16:])
|
||||
in.WindowsVer = be.Uint32(b[0x1A:])
|
||||
in.MemoryMode = b[0x1E]
|
||||
in.Width, in.Height = be.Uint16(b[0x1F:]), be.Uint16(b[0x21:])
|
||||
in.Colors = be.Uint16(b[0x23:])
|
||||
in.Region = be.Uint16(b[0x26:])
|
||||
for i := range in.Language {
|
||||
in.Language[i] = be.Uint16(b[0x28+2*i:])
|
||||
}
|
||||
in.ConnectSpeed = b[0x30]
|
||||
return in
|
||||
}
|
||||
|
||||
func (in Init) String() string {
|
||||
p := fmt.Sprintf("platform %d", in.Platform)
|
||||
switch in.Platform {
|
||||
case PlatformWindows:
|
||||
p = "Windows"
|
||||
case PlatformMac:
|
||||
p = "Macintosh"
|
||||
}
|
||||
s := fmt.Sprintf("%s client, version %d/%d", p, in.Version, in.SubVersion)
|
||||
if in.Width != 0 {
|
||||
s += fmt.Sprintf(", %dx%d", in.Width, in.Height)
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
package p3
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Options tune a Link; the zero value is the client's own timings.
|
||||
type Options struct {
|
||||
// Timeout is how long DATA may go unacknowledged before a HEARTBEAT
|
||||
// asks (12 seconds), and Retries how many are asked before the link is
|
||||
// given up (10).
|
||||
Timeout time.Duration
|
||||
Retries int
|
||||
|
||||
// Window is the most DATA unacknowledged at once (16); AckEvery the
|
||||
// most DATA taken in before it is acknowledged (8), and AckDelay how
|
||||
// long a lone DATA waits for an answer to carry its acknowledgement
|
||||
// before an ACK is sent (200ms).
|
||||
Window int
|
||||
AckEvery int
|
||||
AckDelay time.Duration
|
||||
|
||||
// InitWait is how long Serve waits for the client's INIT (30 seconds).
|
||||
InitWait time.Duration
|
||||
|
||||
// Logf, if set, is told of what goes wrong on the link.
|
||||
Logf func(format string, args ...any)
|
||||
|
||||
// Trace, if set, is given every packet: in, true for one from the
|
||||
// client.
|
||||
Trace func(in bool, p Packet)
|
||||
}
|
||||
|
||||
func (o *Options) defaults() {
|
||||
if o.Timeout <= 0 {
|
||||
o.Timeout = 12 * time.Second
|
||||
}
|
||||
if o.Retries <= 0 {
|
||||
o.Retries = 10
|
||||
}
|
||||
if o.Window <= 0 || o.Window > seqRing/2 {
|
||||
o.Window = 16
|
||||
}
|
||||
if o.AckEvery <= 0 {
|
||||
o.AckEvery = 8
|
||||
}
|
||||
if o.AckDelay <= 0 {
|
||||
o.AckDelay = 200 * time.Millisecond
|
||||
}
|
||||
if o.InitWait <= 0 {
|
||||
o.InitWait = 30 * time.Second
|
||||
}
|
||||
}
|
||||
|
||||
// Errors on a link.
|
||||
var (
|
||||
ErrClosed = errors.New("p3: link closed")
|
||||
ErrTimeout = errors.New("p3: the client stopped acknowledging")
|
||||
ErrNoInit = errors.New("p3: the client sent no INIT")
|
||||
ErrTooBig = fmt.Errorf("p3: more than %d bytes of data", MaxData)
|
||||
)
|
||||
|
||||
// Link is the host's end of a P3 link: DATA in order in, DATA out within
|
||||
// the window, acknowledged, NAKed and resent as P3 does.
|
||||
type Link struct {
|
||||
conn io.ReadWriteCloser
|
||||
r *Reader
|
||||
opt Options
|
||||
|
||||
mu sync.Mutex
|
||||
room *sync.Cond // the window has room, or the link is down
|
||||
init Init
|
||||
tx uint8 // the last DATA sent
|
||||
rx uint8 // the last DATA taken in
|
||||
out []sent // DATA sent, not yet acknowledged
|
||||
pending int // DATA taken in, not yet acknowledged
|
||||
nakked bool // a NAK is out for the gap in what came in
|
||||
hbTries int // HEARTBEATs since the last acknowledgement
|
||||
ackDue bool // an ACK is to go if nothing else does first
|
||||
resent time.Time
|
||||
ackT *time.Timer
|
||||
hbT *time.Timer
|
||||
|
||||
err error // why the link is down: set before done closes
|
||||
|
||||
wq chan []byte // packets to write, in order
|
||||
in chan []byte // DATA come in, in order
|
||||
done chan struct{} // closed when the link is down
|
||||
closed sync.Once
|
||||
}
|
||||
|
||||
type sent struct {
|
||||
seq uint8
|
||||
data []byte
|
||||
}
|
||||
|
||||
// Serve starts the host's end of a link on conn, a connection on which an
|
||||
// AOL client has begun P3: it waits for the client's INIT, acknowledges
|
||||
// it, and the link is up. Close the link to close conn.
|
||||
func Serve(conn io.ReadWriteCloser, opt Options) (*Link, error) {
|
||||
opt.defaults()
|
||||
l := &Link{
|
||||
conn: conn, r: NewReader(conn), opt: opt,
|
||||
tx: SeqInit, rx: SeqInit,
|
||||
wq: make(chan []byte, 256), in: make(chan []byte, 64), done: make(chan struct{}),
|
||||
}
|
||||
l.room = sync.NewCond(&l.mu)
|
||||
type deadliner interface{ SetReadDeadline(time.Time) error }
|
||||
dl, _ := conn.(deadliner)
|
||||
if dl != nil {
|
||||
dl.SetReadDeadline(time.Now().Add(opt.InitWait))
|
||||
}
|
||||
for {
|
||||
p, err := l.r.Read()
|
||||
if err == ErrCRC || err == ErrLength {
|
||||
continue // the client sends its INIT again
|
||||
}
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return nil, ErrNoInit
|
||||
}
|
||||
return nil, fmt.Errorf("%w: %v", ErrNoInit, err)
|
||||
}
|
||||
l.trace(true, p)
|
||||
if p.Kind() == INIT {
|
||||
l.init = ParseInit(p.Data)
|
||||
l.rx = p.TX
|
||||
break
|
||||
}
|
||||
}
|
||||
if dl != nil {
|
||||
dl.SetReadDeadline(time.Time{})
|
||||
}
|
||||
go l.writer()
|
||||
l.mu.Lock()
|
||||
l.send(ACK, nil)
|
||||
l.mu.Unlock()
|
||||
go l.reader()
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// Init is what the client said of itself.
|
||||
func (l *Link) Init() Init {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.init
|
||||
}
|
||||
|
||||
// Read gives the next DATA packet's data from the client.
|
||||
func (l *Link) Read() ([]byte, error) {
|
||||
select {
|
||||
case d := <-l.in:
|
||||
return d, nil
|
||||
case <-l.done:
|
||||
select {
|
||||
case d := <-l.in:
|
||||
return d, nil
|
||||
default:
|
||||
}
|
||||
return nil, l.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// Write sends data to the client in one DATA packet, waiting while the
|
||||
// window is full.
|
||||
func (l *Link) Write(data []byte) error {
|
||||
if len(data) > MaxData {
|
||||
return ErrTooBig
|
||||
}
|
||||
data = append([]byte(nil), data...)
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
for !l.down() && len(l.out) >= l.opt.Window {
|
||||
l.room.Wait()
|
||||
}
|
||||
if l.down() {
|
||||
return l.err
|
||||
}
|
||||
l.tx = next(l.tx)
|
||||
l.out = append(l.out, sent{l.tx, data})
|
||||
if len(l.out) == 1 {
|
||||
l.armHeartbeat()
|
||||
}
|
||||
l.send(DATA, data)
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteToken sends a token and what follows it in one DATA packet.
|
||||
func (l *Link) WriteToken(token string, data []byte) error {
|
||||
if len(token) != 2 {
|
||||
return fmt.Errorf("p3: token %q is not two letters", token)
|
||||
}
|
||||
return l.Write(append([]byte(token), data...))
|
||||
}
|
||||
|
||||
// Unacked is how many DATA packets the client has yet to acknowledge.
|
||||
func (l *Link) Unacked() int {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return len(l.out)
|
||||
}
|
||||
|
||||
// Close takes the link down and closes its connection, once what has been
|
||||
// written has gone (or a second has passed).
|
||||
func (l *Link) Close() error {
|
||||
select {
|
||||
case l.wq <- nil: // the writer closes when it comes to it
|
||||
select {
|
||||
case <-l.done:
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
case <-l.done:
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
l.fail(ErrClosed)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Done is closed when the link is down.
|
||||
func (l *Link) Done() <-chan struct{} { return l.done }
|
||||
|
||||
// Err is why the link is down, or nil.
|
||||
func (l *Link) Err() error {
|
||||
if l.down() {
|
||||
return l.err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *Link) down() bool {
|
||||
select {
|
||||
case <-l.done:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// fail takes the link down for err, the first time. It is called without
|
||||
// l.mu: a sender holding it may be waiting on the writer.
|
||||
func (l *Link) fail(err error) {
|
||||
first := false
|
||||
l.closed.Do(func() {
|
||||
first = true
|
||||
l.err = err
|
||||
close(l.done)
|
||||
l.conn.Close()
|
||||
})
|
||||
if first {
|
||||
if err != ErrClosed {
|
||||
l.logf("link down: %v", err)
|
||||
}
|
||||
l.mu.Lock()
|
||||
l.stopTimers()
|
||||
l.room.Broadcast()
|
||||
l.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Link) stopTimers() {
|
||||
if l.ackT != nil {
|
||||
l.ackT.Stop()
|
||||
}
|
||||
if l.hbT != nil {
|
||||
l.hbT.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Link) logf(format string, args ...any) {
|
||||
if l.opt.Logf != nil {
|
||||
l.opt.Logf("p3: "+format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Link) trace(in bool, p Packet) {
|
||||
if l.opt.Trace != nil {
|
||||
l.opt.Trace(in, p)
|
||||
}
|
||||
}
|
||||
|
||||
// send numbers a packet and queues it to be written; l.mu is held. Every
|
||||
// packet carries the acknowledgement of what has come in.
|
||||
func (l *Link) send(kind uint8, data []byte) {
|
||||
l.sendSeq(l.tx, kind, data)
|
||||
}
|
||||
|
||||
func (l *Link) sendSeq(tx, kind uint8, data []byte) {
|
||||
if l.down() {
|
||||
return
|
||||
}
|
||||
p := Packet{TX: tx, RX: l.rx, Type: kind, Data: data}
|
||||
l.pending, l.ackDue = 0, false
|
||||
l.trace(false, p)
|
||||
select {
|
||||
case l.wq <- Append(nil, p):
|
||||
case <-l.done:
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Link) writer() {
|
||||
type deadliner interface{ SetWriteDeadline(time.Time) error }
|
||||
dl, _ := l.conn.(deadliner)
|
||||
for {
|
||||
select {
|
||||
case b := <-l.wq:
|
||||
if b == nil {
|
||||
l.fail(ErrClosed)
|
||||
return
|
||||
}
|
||||
if dl != nil {
|
||||
dl.SetWriteDeadline(time.Now().Add(l.opt.Timeout * time.Duration(l.opt.Retries)))
|
||||
}
|
||||
if _, err := l.conn.Write(b); err != nil {
|
||||
l.fail(err)
|
||||
return
|
||||
}
|
||||
case <-l.done:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Link) reader() {
|
||||
for {
|
||||
p, err := l.r.Read()
|
||||
switch {
|
||||
case err == ErrCRC:
|
||||
l.trace(true, p)
|
||||
l.nak(NakCRC)
|
||||
continue
|
||||
case err == ErrLength:
|
||||
l.nak(NakLength)
|
||||
continue
|
||||
case err != nil:
|
||||
l.fail(err)
|
||||
return
|
||||
}
|
||||
l.trace(true, p)
|
||||
if d := l.take(p); d != nil {
|
||||
select {
|
||||
case l.in <- d:
|
||||
case <-l.done:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// nak asks the client to resend from the first DATA after our rx, once
|
||||
// for each gap in what came in.
|
||||
func (l *Link) nak(reason uint8) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if !l.nakked {
|
||||
l.nakked = true
|
||||
l.send(NAK, []byte{reason})
|
||||
}
|
||||
}
|
||||
|
||||
// take handles a packet from the client, and gives DATA's data to be
|
||||
// read.
|
||||
func (l *Link) take(p Packet) []byte {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if p.Kind() == INIT {
|
||||
// the client has started again (or missed our ACK): so do we
|
||||
if len(l.out) > 0 || l.rx != p.TX {
|
||||
l.logf("INIT again, %d packets unsent", len(l.out))
|
||||
}
|
||||
l.init = ParseInit(p.Data)
|
||||
l.tx, l.rx, l.out, l.nakked, l.hbTries = SeqInit, p.TX, nil, false, 0
|
||||
l.stopTimers()
|
||||
l.room.Broadcast()
|
||||
l.send(ACK, nil)
|
||||
return nil
|
||||
}
|
||||
heartbeat := l.hbTries > 0
|
||||
l.acked(p.RX)
|
||||
switch p.Kind() {
|
||||
case DATA:
|
||||
switch {
|
||||
case p.TX == next(l.rx):
|
||||
l.rx = p.TX
|
||||
l.nakked = false
|
||||
l.pending++
|
||||
if l.pending >= l.opt.AckEvery {
|
||||
l.send(ACK, nil)
|
||||
} else {
|
||||
l.armAck()
|
||||
}
|
||||
return p.Data
|
||||
case behind(p.TX, l.rx) < seqRing/2:
|
||||
// one we have: our acknowledgement went astray
|
||||
l.armAck()
|
||||
default:
|
||||
if !l.nakked {
|
||||
l.nakked = true
|
||||
l.send(NAK, []byte{NakSequence})
|
||||
}
|
||||
}
|
||||
case ACK:
|
||||
if heartbeat {
|
||||
l.resend(p.RX)
|
||||
}
|
||||
case NAK:
|
||||
if len(p.Data) > 0 && p.Data[0] != NakSequence {
|
||||
l.logf("NAK %d from rx %02x", p.Data[0], p.RX)
|
||||
}
|
||||
l.resend(p.RX)
|
||||
case HEARTBEAT:
|
||||
l.send(ACK, nil)
|
||||
case SS:
|
||||
l.send(SSR, nil)
|
||||
case SSR:
|
||||
l.resend(p.RX)
|
||||
default:
|
||||
l.logf("packet type %02x", p.Type)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// acked takes rx as the client's acknowledgement of our DATA up to it.
|
||||
func (l *Link) acked(rx uint8) {
|
||||
for i, s := range l.out {
|
||||
if s.seq == rx {
|
||||
l.out = l.out[i+1:]
|
||||
l.hbTries = 0
|
||||
if len(l.out) > 0 {
|
||||
l.armHeartbeat()
|
||||
} else if l.hbT != nil {
|
||||
l.hbT.Stop()
|
||||
}
|
||||
l.room.Broadcast()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// resend sends again all the DATA not acknowledged (go back N), but not
|
||||
// twice over for one loss.
|
||||
func (l *Link) resend(rx uint8) {
|
||||
if len(l.out) == 0 || time.Since(l.resent) < l.opt.AckDelay {
|
||||
return
|
||||
}
|
||||
l.resent = time.Now()
|
||||
for _, s := range l.out {
|
||||
l.sendSeq(s.seq, DATA, s.data)
|
||||
}
|
||||
l.armHeartbeat()
|
||||
}
|
||||
|
||||
// armAck has an ACK sent soon, unless another packet carries the
|
||||
// acknowledgement first.
|
||||
func (l *Link) armAck() {
|
||||
if l.ackDue {
|
||||
return
|
||||
}
|
||||
l.ackDue = true
|
||||
if l.ackT == nil {
|
||||
l.ackT = time.AfterFunc(l.opt.AckDelay, func() {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.ackDue {
|
||||
l.send(ACK, nil)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
l.ackT.Reset(l.opt.AckDelay)
|
||||
}
|
||||
}
|
||||
func (l *Link) armHeartbeat() {
|
||||
if l.hbT == nil {
|
||||
l.hbT = time.AfterFunc(l.opt.Timeout, l.heartbeat)
|
||||
} else {
|
||||
l.hbT.Reset(l.opt.Timeout)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Link) heartbeat() {
|
||||
l.mu.Lock()
|
||||
if l.down() || len(l.out) == 0 {
|
||||
l.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if l.hbTries >= l.opt.Retries {
|
||||
l.mu.Unlock()
|
||||
l.fail(ErrTimeout)
|
||||
return
|
||||
}
|
||||
l.hbTries++
|
||||
l.send(HEARTBEAT, nil)
|
||||
l.hbT.Reset(l.opt.Timeout)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
// Package p3 is P3, the link layer under the classic AOL client (3.0, 4.0
|
||||
// and on): the packets that carry its tokens and atom streams to the host,
|
||||
// over a modem or inside TCP on port 5190, numbered, checked and
|
||||
// acknowledged.
|
||||
//
|
||||
// A packet is
|
||||
//
|
||||
// 5A crc(2) length(2) tx rx type data... 0D
|
||||
//
|
||||
// the CRC a CRC-16/ARC of everything from the length to the last data byte,
|
||||
// the length that of tx, rx, type and data. DATA packets are numbered by
|
||||
// tx from 0x10 to 0x7F and round again, and each side's rx acknowledges
|
||||
// every packet up to the one it names; the rest (ACK, NAK, HEARTBEAT,
|
||||
// INIT, SS, SSR) repeat the last DATA number. A sender has at most 16
|
||||
// packets unacknowledged; a receiver acknowledges at least every 8th; 12
|
||||
// seconds without one and the sender asks with a HEARTBEAT, up to 10 times.
|
||||
// The client sets the top bit of the type (A0, A3, A4...), so a packet
|
||||
// echoed back by a line is told from the host's; the host sends types bare.
|
||||
//
|
||||
// The client opens with INIT (its version, its machine) at 7F/7F, and the
|
||||
// link is up when the host acknowledges it. AOL 4.0 over TCP stops
|
||||
// computing CRCs after that and sends "**" in their place.
|
||||
//
|
||||
// Reader and Append read and write packets; Link is the host's end of a
|
||||
// link, which Serve starts on a connection.
|
||||
//
|
||||
// Sources: Deceptio's P3 pages (deceptio.org/re/p3), written with the
|
||||
// help of P3's author; the FDO91 manual's chapter 27; and what Dialtone
|
||||
// and others have learned serving live clients.
|
||||
package p3
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Sync and End begin and end every packet.
|
||||
const (
|
||||
Sync = 0x5A
|
||||
End = 0x0D
|
||||
)
|
||||
|
||||
// The packet types.
|
||||
const (
|
||||
DATA = 0x20
|
||||
SS = 0x21 // asks for an SSR
|
||||
SSR = 0x22 // answers an SS: resend what follows my rx
|
||||
INIT = 0x23 // the client's first packet
|
||||
ACK = 0x24
|
||||
NAK = 0x25 // data: why (NakCRC, NakSequence, NakLength)
|
||||
HEARTBEAT = 0x26 // asks for an ACK
|
||||
|
||||
// FromClient is set in the type of every packet the client sends.
|
||||
FromClient = 0x80
|
||||
)
|
||||
|
||||
// A NAK's reason, its one byte of data.
|
||||
const (
|
||||
NakCRC = 1
|
||||
NakSequence = 2
|
||||
NakLength = 3
|
||||
)
|
||||
|
||||
// Sequence numbers.
|
||||
const (
|
||||
SeqMin = 0x10
|
||||
SeqMax = 0x7F
|
||||
SeqInit = 0x7F // both sides' tx and rx before any DATA
|
||||
seqRing = SeqMax - SeqMin + 1
|
||||
)
|
||||
|
||||
// Sizes.
|
||||
const (
|
||||
// MaxLength is the largest length a packet may have (1,024 bytes in
|
||||
// all); MaxData is the most data in one packet.
|
||||
MaxLength = 0x3FA
|
||||
MaxData = MaxLength - 3
|
||||
|
||||
// MaxClientData is the most the client puts in one packet.
|
||||
MaxClientData = 0x77
|
||||
|
||||
headerSize = 8
|
||||
)
|
||||
|
||||
// noCRC is what AOL 4.0 over TCP sends for a CRC.
|
||||
const noCRC = 0x2A2A
|
||||
|
||||
// Packet is a P3 packet.
|
||||
type Packet struct {
|
||||
TX, RX uint8
|
||||
Type uint8 // as sent: the client's have FromClient set
|
||||
Data []byte
|
||||
NoCRC bool // read: its CRC was "**", not checked
|
||||
}
|
||||
|
||||
// Kind is p's type without FromClient.
|
||||
func (p Packet) Kind() uint8 { return p.Type &^ FromClient }
|
||||
|
||||
// FromClient is whether the client sent p.
|
||||
func (p Packet) FromClient() bool { return p.Type&FromClient != 0 }
|
||||
|
||||
func (p Packet) String() string {
|
||||
name, ok := typeNames[p.Kind()]
|
||||
if !ok {
|
||||
name = fmt.Sprintf("type %02x", p.Type)
|
||||
}
|
||||
s := fmt.Sprintf("%s tx=%02x rx=%02x", name, p.TX, p.RX)
|
||||
if p.Kind() == DATA && len(p.Data) >= 2 {
|
||||
s += fmt.Sprintf(" %q", p.Data[:2])
|
||||
}
|
||||
if len(p.Data) > 0 {
|
||||
s += fmt.Sprintf(" (%d bytes)", len(p.Data))
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
var typeNames = map[uint8]string{
|
||||
DATA: "DATA", SS: "SS", SSR: "SSR", INIT: "INIT", ACK: "ACK", NAK: "NAK", HEARTBEAT: "HEARTBEAT",
|
||||
}
|
||||
|
||||
// CRC is P3's CRC: CRC-16/ARC (reflected 0x8005, from zero).
|
||||
func CRC(b []byte) uint16 {
|
||||
var c uint16
|
||||
for _, x := range b {
|
||||
c = c>>8 ^ crcTable[byte(c)^x]
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
var crcTable = func() (t [256]uint16) {
|
||||
for i := range t {
|
||||
c := uint16(i)
|
||||
for range 8 {
|
||||
if c&1 != 0 {
|
||||
c = c>>1 ^ 0xA001
|
||||
} else {
|
||||
c >>= 1
|
||||
}
|
||||
}
|
||||
t[i] = c
|
||||
}
|
||||
return
|
||||
}()
|
||||
|
||||
// Append appends p as bytes to b, with its length and CRC. It panics on
|
||||
// more than MaxData of data.
|
||||
func Append(b []byte, p Packet) []byte {
|
||||
if len(p.Data) > MaxData {
|
||||
panic(fmt.Sprintf("p3: %d bytes of data in one packet", len(p.Data)))
|
||||
}
|
||||
n := len(p.Data) + 3
|
||||
start := len(b)
|
||||
b = append(b, Sync, 0, 0, byte(n>>8), byte(n), p.TX, p.RX, p.Type)
|
||||
b = append(b, p.Data...)
|
||||
c := CRC(b[start+3:])
|
||||
b[start+1], b[start+2] = byte(c>>8), byte(c)
|
||||
return append(b, End)
|
||||
}
|
||||
|
||||
// Errors reading packets. A packet with ErrCRC or ErrLength is to be
|
||||
// NAKed; the Reader has passed over it and goes on with the next.
|
||||
var (
|
||||
ErrCRC = errors.New("p3: bad CRC")
|
||||
ErrLength = errors.New("p3: bad length")
|
||||
)
|
||||
|
||||
// Reader reads packets.
|
||||
type Reader struct {
|
||||
r *bufio.Reader
|
||||
Skipped int // bytes passed over looking for a packet
|
||||
}
|
||||
|
||||
// NewReader reads packets from r.
|
||||
func NewReader(r io.Reader) *Reader {
|
||||
br, ok := r.(*bufio.Reader)
|
||||
if !ok || br.Size() < MaxLength+6 {
|
||||
br = bufio.NewReaderSize(r, 4096)
|
||||
}
|
||||
return &Reader{r: br}
|
||||
}
|
||||
|
||||
// Read reads the next packet. Bytes before a Sync are passed over; a
|
||||
// packet whose CRC is wrong is ErrCRC, one too long or short ErrLength.
|
||||
// A packet without its End is taken as it is.
|
||||
func (r *Reader) Read() (Packet, error) {
|
||||
for {
|
||||
c, err := r.r.ReadByte()
|
||||
if err != nil {
|
||||
return Packet{}, err
|
||||
}
|
||||
if c == Sync {
|
||||
break
|
||||
}
|
||||
r.Skipped++
|
||||
}
|
||||
h, err := r.r.Peek(4)
|
||||
if err != nil {
|
||||
return Packet{}, unexpected(err)
|
||||
}
|
||||
n := int(h[2])<<8 | int(h[3])
|
||||
if n < 3 || n > MaxLength {
|
||||
// line noise, most likely: look for the next Sync from here
|
||||
return Packet{}, ErrLength
|
||||
}
|
||||
b, err := r.r.Peek(4 + n)
|
||||
if err != nil {
|
||||
return Packet{}, unexpected(err)
|
||||
}
|
||||
crc := uint16(b[0])<<8 | uint16(b[1])
|
||||
p := Packet{TX: b[4], RX: b[5], Type: b[6], NoCRC: crc == noCRC}
|
||||
ok := p.NoCRC || CRC(b[2:]) == crc
|
||||
p.Data = append([]byte(nil), b[7:]...)
|
||||
r.r.Discard(4 + n)
|
||||
if e, err := r.r.Peek(1); err == nil && e[0] == End {
|
||||
r.r.Discard(1)
|
||||
}
|
||||
if !ok {
|
||||
return p, ErrCRC
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func unexpected(err error) error {
|
||||
if err == io.EOF {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Sniff is whether b begins as a P3 client's first packet, an INIT.
|
||||
func Sniff(b []byte) bool {
|
||||
return len(b) >= headerSize && b[0] == Sync && b[7]&^FromClient == INIT
|
||||
}
|
||||
|
||||
// Token splits a DATA packet's data into its token (two letters, "Dd",
|
||||
// "Aa"...) and what follows it.
|
||||
func Token(data []byte) (string, []byte) {
|
||||
if len(data) < 2 {
|
||||
return "", data
|
||||
}
|
||||
return string(data[:2]), data[2:]
|
||||
}
|
||||
|
||||
// next is the sequence number after s.
|
||||
func next(s uint8) uint8 {
|
||||
if s >= SeqMax || s < SeqMin {
|
||||
return SeqMin
|
||||
}
|
||||
return s + 1
|
||||
}
|
||||
|
||||
// behind is how far s is behind t, round the ring: 0 if s is t.
|
||||
func behind(s, t uint8) int {
|
||||
return ((int(t)-int(s))%seqRing + seqRing) % seqRing
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
package p3
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func unhex(s string) []byte {
|
||||
b, err := hex.DecodeString(strings.ReplaceAll(s, " ", ""))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// Packets a host sends live clients (as Dialtone, which serves them, has
|
||||
// them): the ACK of the client's INIT and the SD that follows it; and a
|
||||
// sign-off (XS) with AOL 4.0's "**" for a CRC.
|
||||
var (
|
||||
initACK = unhex("5ab71100037f7f240d")
|
||||
sdData = unhex("5a88e9000b107f20534454d1f68b00000d")
|
||||
xsBye = unhex("5a2a2a000d7f7f20585347 6f6f64627965210d")
|
||||
)
|
||||
|
||||
func TestPackets(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
raw []byte
|
||||
p Packet
|
||||
}{
|
||||
{initACK, Packet{TX: 0x7F, RX: 0x7F, Type: ACK}},
|
||||
{sdData, Packet{TX: 0x10, RX: 0x7F, Type: DATA, Data: unhex("5344 54d1f68b0000")}},
|
||||
} {
|
||||
if got := Append(nil, c.p); !bytes.Equal(got, c.raw) {
|
||||
t.Errorf("Append(%v) = %x, want %x", c.p, got, c.raw)
|
||||
}
|
||||
p, err := NewReader(bytes.NewReader(c.raw)).Read()
|
||||
if err != nil || p.TX != c.p.TX || p.RX != c.p.RX || p.Type != c.p.Type || !bytes.Equal(p.Data, c.p.Data) || p.NoCRC {
|
||||
t.Errorf("Read(%x) = %v, %v", c.raw, p, err)
|
||||
}
|
||||
}
|
||||
p, err := NewReader(bytes.NewReader(xsBye)).Read()
|
||||
if tok, rest := Token(p.Data); err != nil || !p.NoCRC || tok != "XS" || string(rest) != "Goodbye!" {
|
||||
t.Errorf("Read(**) = %v, %v", p, err)
|
||||
}
|
||||
if CRC([]byte("123456789")) != 0xBB3D { // CRC-16/ARC's check value
|
||||
t.Error("CRC")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReader(t *testing.T) {
|
||||
bad := append([]byte(nil), sdData...)
|
||||
bad[len(bad)-2] ^= 1
|
||||
noEnd := initACK[:len(initACK)-1]
|
||||
var in []byte
|
||||
in = append(in, "ATDT\r"...) // what isn't P3 is passed over
|
||||
in = append(in, initACK...)
|
||||
in = append(in, bad...)
|
||||
in = append(in, 0x5A, 0x00, 0x00, 0xFF, 0xFF) // a length too long
|
||||
in = append(in, noEnd...)
|
||||
in = append(in, sdData...)
|
||||
in = append(in, Append(nil, Packet{TX: 0x11, RX: 0x7F, Type: DATA, Data: bytes.Repeat([]byte{End}, 30)})...)
|
||||
r := NewReader(bytes.NewReader(in))
|
||||
var got []string
|
||||
for {
|
||||
p, err := r.Read()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
switch err {
|
||||
case nil:
|
||||
got = append(got, fmt.Sprintf("%02x/%d", p.Type, len(p.Data)))
|
||||
case ErrCRC, ErrLength:
|
||||
got = append(got, err.Error())
|
||||
default:
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
want := "24/0 p3: bad CRC p3: bad length 24/0 20/8 20/30"
|
||||
if g := strings.Join(got, " "); g != want {
|
||||
t.Errorf("got %s\nwant %s", g, want)
|
||||
}
|
||||
if r.Skipped != 5+4 {
|
||||
t.Errorf("skipped %d", r.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeq(t *testing.T) {
|
||||
if next(0x7F) != 0x10 || next(0x10) != 0x11 || next(0) != 0x10 {
|
||||
t.Error("next")
|
||||
}
|
||||
if behind(0x7F, 0x10) != 1 || behind(0x10, 0x7F) != seqRing-1 || behind(0x20, 0x20) != 0 {
|
||||
t.Error("behind")
|
||||
}
|
||||
}
|
||||
|
||||
// initData is an INIT as the 32-bit Windows client lays it out.
|
||||
func initData() []byte {
|
||||
d := make([]byte, 0x34)
|
||||
d[0], d[1], d[2] = PlatformWindows, 3, 0
|
||||
d[0x1F], d[0x20], d[0x21], d[0x22] = 0x03, 0x20, 0x02, 0x58 // 800x600
|
||||
d[0x30] = 5
|
||||
return d
|
||||
}
|
||||
|
||||
func TestInit(t *testing.T) {
|
||||
in := ParseInit(initData())
|
||||
if in.Platform != PlatformWindows || in.Width != 800 || in.Height != 600 || in.ConnectSpeed != 5 {
|
||||
t.Errorf("%+v", in)
|
||||
}
|
||||
if s := in.String(); s != "Windows client, version 3/0, 800x600" {
|
||||
t.Error(s)
|
||||
}
|
||||
if in := ParseInit([]byte{PlatformMac, 2}); in.Platform != PlatformMac || in.Version != 2 {
|
||||
t.Errorf("short: %+v", in)
|
||||
}
|
||||
if !Sniff(Append(nil, Packet{TX: 0x7F, RX: 0x7F, Type: INIT | FromClient, Data: initData()})) || Sniff(sdData) || Sniff([]byte("*\x01")) {
|
||||
t.Error("Sniff")
|
||||
}
|
||||
}
|
||||
|
||||
// client is the client's end of a link, scripted by a test.
|
||||
type client struct {
|
||||
t *testing.T
|
||||
c net.Conn
|
||||
pkts chan Packet
|
||||
errs chan error
|
||||
}
|
||||
|
||||
func dial(t *testing.T, opt Options) (*client, *Link) {
|
||||
t.Helper()
|
||||
a, b := net.Pipe()
|
||||
c := &client{t: t, c: a, pkts: make(chan Packet, 1024), errs: make(chan error, 64)}
|
||||
go func() {
|
||||
r := NewReader(bufio.NewReader(a))
|
||||
for {
|
||||
p, err := r.Read()
|
||||
if err == ErrCRC || err == ErrLength {
|
||||
c.errs <- err
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
close(c.pkts)
|
||||
return
|
||||
}
|
||||
c.pkts <- p
|
||||
}
|
||||
}()
|
||||
var l *Link
|
||||
done := make(chan error)
|
||||
go func() {
|
||||
var err error
|
||||
l, err = Serve(b, opt)
|
||||
done <- err
|
||||
}()
|
||||
c.send(Packet{TX: SeqInit, RX: SeqInit, Type: INIT, Data: initData()})
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p := c.expect(ACK); p.TX != 0x7F || p.RX != 0x7F {
|
||||
t.Fatalf("INIT answered with %v", p)
|
||||
}
|
||||
t.Cleanup(func() { l.Close(); a.Close() })
|
||||
return c, l
|
||||
}
|
||||
|
||||
func (c *client) send(p Packet) {
|
||||
p.Type |= FromClient
|
||||
if _, err := c.c.Write(Append(nil, p)); err != nil {
|
||||
c.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *client) next() (Packet, bool) {
|
||||
select {
|
||||
case p, ok := <-c.pkts:
|
||||
return p, ok
|
||||
case <-time.After(2 * time.Second):
|
||||
c.t.Fatal("nothing from the host")
|
||||
return Packet{}, false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *client) expect(kind uint8) Packet {
|
||||
c.t.Helper()
|
||||
p, ok := c.next()
|
||||
if !ok {
|
||||
c.t.Fatalf("link closed, wanted %02x", kind)
|
||||
}
|
||||
if p.Type != kind {
|
||||
c.t.Fatalf("got %v, wanted %02x", p, kind)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (c *client) quiet(d time.Duration) {
|
||||
c.t.Helper()
|
||||
select {
|
||||
case p := <-c.pkts:
|
||||
c.t.Fatalf("unexpected %v", p)
|
||||
case <-time.After(d):
|
||||
}
|
||||
}
|
||||
|
||||
func read(t *testing.T, l *Link) []byte {
|
||||
t.Helper()
|
||||
got := make(chan []byte, 1)
|
||||
go func() {
|
||||
d, err := l.Read()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
got <- d
|
||||
}()
|
||||
select {
|
||||
case d := <-got:
|
||||
return d
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("nothing read")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandshake(t *testing.T) {
|
||||
a, b := net.Pipe()
|
||||
defer a.Close()
|
||||
go a.Write(Append(nil, Packet{TX: SeqInit, RX: SeqInit, Type: INIT | FromClient, Data: initData()}))
|
||||
got := make(chan []byte)
|
||||
go func() {
|
||||
buf := make([]byte, 64)
|
||||
n, _ := a.Read(buf)
|
||||
got <- buf[:n]
|
||||
}()
|
||||
l, err := Serve(b, Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
if g := <-got; !bytes.Equal(g, initACK) {
|
||||
t.Errorf("INIT answered with %x, want %x", g, initACK)
|
||||
}
|
||||
if in := l.Init(); in.Width != 800 {
|
||||
t.Errorf("Init: %+v", in)
|
||||
}
|
||||
|
||||
// no INIT: Serve gives up
|
||||
a2, b2 := net.Pipe()
|
||||
go func() { a2.Write([]byte("hello\r")); a2.Close() }()
|
||||
if _, err := Serve(b2, Options{InitWait: time.Second}); !errors.Is(err, ErrNoInit) {
|
||||
t.Errorf("no INIT: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestData(t *testing.T) {
|
||||
c, l := dial(t, Options{AckDelay: 20 * time.Millisecond})
|
||||
|
||||
// the client's DATA is read, and acknowledged soon after
|
||||
c.send(Packet{TX: 0x10, RX: 0x7F, Type: DATA, Data: []byte("Dd\x00\x15")})
|
||||
if d := read(t, l); string(d) != "Dd\x00\x15" {
|
||||
t.Errorf("read %q", d)
|
||||
}
|
||||
if p := c.expect(ACK); p.RX != 0x10 || p.TX != 0x7F {
|
||||
t.Errorf("ACK %v", p)
|
||||
}
|
||||
|
||||
// the host's DATA carries the acknowledgement: no ACK as well
|
||||
c.send(Packet{TX: 0x11, RX: 0x7F, Type: DATA, Data: []byte("ya")})
|
||||
read(t, l)
|
||||
if err := l.WriteToken("SD", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p := c.expect(DATA); p.TX != 0x10 || p.RX != 0x11 || string(p.Data) != "SD" {
|
||||
t.Errorf("DATA %v", p)
|
||||
}
|
||||
c.quiet(60 * time.Millisecond)
|
||||
if l.Unacked() != 1 {
|
||||
t.Errorf("unacked %d", l.Unacked())
|
||||
}
|
||||
c.send(Packet{TX: 0x11, RX: 0x10, Type: ACK})
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if l.Unacked() != 0 {
|
||||
t.Errorf("unacked %d after ACK", l.Unacked())
|
||||
}
|
||||
|
||||
// a DATA again (our ACK lost): acknowledged, not read twice
|
||||
c.send(Packet{TX: 0x11, RX: 0x10, Type: DATA, Data: []byte("ya")})
|
||||
if p := c.expect(ACK); p.RX != 0x11 {
|
||||
t.Errorf("ACK %v", p)
|
||||
}
|
||||
|
||||
// one missing: NAKed once, then taken when it comes
|
||||
c.send(Packet{TX: 0x13, RX: 0x10, Type: DATA, Data: []byte("x3")})
|
||||
c.send(Packet{TX: 0x14, RX: 0x10, Type: DATA, Data: []byte("x4")})
|
||||
if p := c.expect(NAK); p.RX != 0x11 || !bytes.Equal(p.Data, []byte{NakSequence}) {
|
||||
t.Errorf("NAK %v", p)
|
||||
}
|
||||
c.quiet(60 * time.Millisecond)
|
||||
for i := uint8(0x12); i <= 0x14; i++ {
|
||||
c.send(Packet{TX: i, RX: 0x10, Type: DATA, Data: []byte{'x', '0' + i - 0x10}})
|
||||
}
|
||||
for _, w := range []string{"x2", "x3", "x4"} {
|
||||
if d := read(t, l); string(d) != w {
|
||||
t.Errorf("read %q, want %q", d, w)
|
||||
}
|
||||
}
|
||||
if p := c.expect(ACK); p.RX != 0x14 {
|
||||
t.Errorf("ACK %v", p)
|
||||
}
|
||||
|
||||
// a bad CRC: NAKed
|
||||
b := Append(nil, Packet{TX: 0x15, RX: 0x10, Type: DATA | FromClient, Data: []byte("zz")})
|
||||
b[1] ^= 0xFF
|
||||
c.c.Write(b)
|
||||
if p := c.expect(NAK); p.RX != 0x14 || !bytes.Equal(p.Data, []byte{NakCRC}) {
|
||||
t.Errorf("NAK %v", p)
|
||||
}
|
||||
|
||||
// a HEARTBEAT: ACKed at once
|
||||
c.send(Packet{TX: 0x14, RX: 0x10, Type: HEARTBEAT})
|
||||
if p := c.expect(ACK); p.RX != 0x14 {
|
||||
t.Errorf("ACK %v", p)
|
||||
}
|
||||
|
||||
// AOL 4.0's "**" CRC
|
||||
b = Append(nil, Packet{TX: 0x15, RX: 0x10, Type: DATA | FromClient, Data: []byte("pE")})
|
||||
b[1], b[2] = '*', '*'
|
||||
c.c.Write(b)
|
||||
if d := read(t, l); string(d) != "pE" {
|
||||
t.Errorf("read %q", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAckEvery(t *testing.T) {
|
||||
c, l := dial(t, Options{AckDelay: time.Hour})
|
||||
seq := uint8(SeqInit)
|
||||
for i := range 8 {
|
||||
seq = next(seq)
|
||||
c.send(Packet{TX: seq, RX: SeqInit, Type: DATA, Data: []byte{'a', byte(i)}})
|
||||
read(t, l)
|
||||
}
|
||||
if p := c.expect(ACK); p.RX != seq {
|
||||
t.Errorf("ACK %v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindow(t *testing.T) {
|
||||
c, l := dial(t, Options{})
|
||||
wrote := make(chan int, 32)
|
||||
go func() {
|
||||
for i := range 20 {
|
||||
if err := l.Write([]byte{'w', byte(i)}); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
wrote <- i
|
||||
}
|
||||
}()
|
||||
var last Packet
|
||||
for range 16 {
|
||||
last = c.expect(DATA)
|
||||
}
|
||||
c.quiet(50 * time.Millisecond)
|
||||
if len(wrote) != 16 || last.TX != 0x1F {
|
||||
t.Fatalf("%d written, last %v", len(wrote), last)
|
||||
}
|
||||
// acknowledging 3 lets 3 more go
|
||||
c.send(Packet{TX: SeqInit, RX: 0x12, Type: ACK})
|
||||
for i := range 3 {
|
||||
if p := c.expect(DATA); p.TX != uint8(0x20+i) {
|
||||
t.Errorf("DATA %v", p)
|
||||
}
|
||||
}
|
||||
c.quiet(50 * time.Millisecond)
|
||||
|
||||
// a NAK has all the unacknowledged sent again, from after its rx
|
||||
c.send(Packet{TX: SeqInit, RX: 0x15, Type: NAK, Data: []byte{NakSequence}})
|
||||
for i := 0x16; i <= 0x22; i++ {
|
||||
if p := c.expect(DATA); p.TX != uint8(i) || p.Data[1] != byte(i-0x10) {
|
||||
t.Fatalf("resent %v, want tx %02x", p, i)
|
||||
}
|
||||
}
|
||||
c.send(Packet{TX: SeqInit, RX: 0x22, Type: ACK})
|
||||
if p := c.expect(DATA); p.TX != 0x23 {
|
||||
t.Errorf("DATA %v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrap(t *testing.T) {
|
||||
c, l := dial(t, Options{AckDelay: time.Millisecond})
|
||||
const n = 300
|
||||
go func() {
|
||||
for i := range n {
|
||||
if err := l.Write([]byte(fmt.Sprint(i))); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
seq, rx := uint8(SeqInit), uint8(SeqInit)
|
||||
for i := 0; i < n; {
|
||||
p, _ := c.next()
|
||||
if p.Type != DATA {
|
||||
continue // its ACKs of ours
|
||||
}
|
||||
if p.TX != next(rx) || string(p.Data) != fmt.Sprint(i) {
|
||||
t.Fatalf("%d: %v %q", i, p, p.Data)
|
||||
}
|
||||
rx = p.TX
|
||||
i++
|
||||
// and the client talks back, acknowledging as it goes
|
||||
seq = next(seq)
|
||||
c.send(Packet{TX: seq, RX: rx, Type: DATA, Data: []byte(fmt.Sprint(i))})
|
||||
if d := read(t, l); string(d) != fmt.Sprint(i) {
|
||||
t.Fatalf("read %q", d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeartbeat(t *testing.T) {
|
||||
c, l := dial(t, Options{Timeout: 30 * time.Millisecond, Retries: 3})
|
||||
l.Write([]byte("aa"))
|
||||
l.Write([]byte("ab"))
|
||||
c.expect(DATA)
|
||||
c.expect(DATA)
|
||||
// no acknowledgement: HEARTBEATs, and the client's ACK of only the
|
||||
// first has the second sent again
|
||||
if p := c.expect(HEARTBEAT); p.TX != 0x11 {
|
||||
t.Errorf("HEARTBEAT %v", p)
|
||||
}
|
||||
c.send(Packet{TX: SeqInit, RX: 0x10, Type: ACK})
|
||||
if p := c.expect(DATA); p.TX != 0x11 || string(p.Data) != "ab" {
|
||||
t.Errorf("resent %v", p)
|
||||
}
|
||||
// then silence: three HEARTBEATs and the link is down
|
||||
for range 3 {
|
||||
c.expect(HEARTBEAT)
|
||||
}
|
||||
select {
|
||||
case <-l.Done():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("link still up")
|
||||
}
|
||||
if l.Err() != ErrTimeout {
|
||||
t.Errorf("Err %v", l.Err())
|
||||
}
|
||||
if err := l.Write([]byte("x")); err != ErrTimeout {
|
||||
t.Errorf("Write after: %v", err)
|
||||
}
|
||||
if _, err := l.Read(); err != ErrTimeout {
|
||||
t.Errorf("Read after: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReinit(t *testing.T) {
|
||||
c, l := dial(t, Options{})
|
||||
l.Write([]byte("aa"))
|
||||
c.expect(DATA)
|
||||
// the client starts over: so does the host
|
||||
c.send(Packet{TX: SeqInit, RX: SeqInit, Type: INIT, Data: initData()})
|
||||
if p := c.expect(ACK); p.TX != SeqInit || p.RX != SeqInit {
|
||||
t.Errorf("ACK %v", p)
|
||||
}
|
||||
l.Write([]byte("ab"))
|
||||
if p := c.expect(DATA); p.TX != 0x10 {
|
||||
t.Errorf("DATA %v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClose(t *testing.T) {
|
||||
c, l := dial(t, Options{})
|
||||
c.c.Close()
|
||||
select {
|
||||
case <-l.Done():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("link still up")
|
||||
}
|
||||
if _, err := l.Read(); err == nil {
|
||||
t.Error("Read after close")
|
||||
}
|
||||
if err := l.Write(make([]byte, MaxData+1)); err != ErrTooBig {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseSends(t *testing.T) {
|
||||
c, l := dial(t, Options{})
|
||||
l.WriteToken("XS", []byte("Goodbye!"))
|
||||
l.Close()
|
||||
if p := c.expect(DATA); string(p.Data) != "XSGoodbye!" {
|
||||
t.Errorf("DATA %v", p)
|
||||
}
|
||||
if _, ok := c.next(); ok {
|
||||
t.Error("not closed")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user