This repository has been archived by the owner on Dec 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxmodem.go
312 lines (276 loc) · 7.82 KB
/
xmodem.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Copyright (c) 2019 S.Merrony - The CRC funcs are borrowed from "chriszzzzz"'s fork of Omegaice's go-xmodem code
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, asciiSUBlicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, asciiSUBject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or asciiSUBstantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"time"
)
const asciiSOH byte = 0x01
const asciiSTX byte = 0x02
const asciiEOT byte = 0x04
const asciiACK byte = 0x06
const asciiNAK byte = 0x15
const asciiCAN byte = 0x18
const asciiSUB byte = 0x1a
const xmodemPOLL byte = 'C'
const xmodemShortPacketLen = 128
const xmodemLongPacketLen = 1024
const ackTimeoutSecs = 5
const dataTimeoutSecs = 10
const pollTimeoutSecs = 30
func crc16(data []byte) uint16 {
var u16CRC uint16
for _, character := range data {
part := uint16(character)
u16CRC = u16CRC ^ (part << 8)
for i := 0; i < 8; i++ {
if u16CRC&0x8000 > 0 {
u16CRC = u16CRC<<1 ^ 0x1021
} else {
u16CRC = u16CRC << 1
}
}
}
return u16CRC
}
func crc16Constant(data []byte, length int) uint16 {
var u16CRC uint16
for _, character := range data {
part := uint16(character)
u16CRC = u16CRC ^ (part << 8)
for i := 0; i < 8; i++ {
if u16CRC&0x8000 > 0 {
u16CRC = u16CRC<<1 ^ 0x1021
} else {
u16CRC = u16CRC << 1
}
}
}
for c := 0; c < length-len(data); c++ {
u16CRC = u16CRC ^ (0x04 << 8)
for i := 0; i < 8; i++ {
if u16CRC&0x8000 > 0 {
u16CRC = u16CRC<<1 ^ 0x1021
} else {
u16CRC = u16CRC << 1
}
}
}
return u16CRC
}
func sendBlock(tx chan byte, block int, data []byte, packetPayloadLen int) error {
startByte := asciiSOH
if packetPayloadLen == xmodemLongPacketLen {
startByte = asciiSTX
}
// send start byte and length
if *xmodemTraceFlag {
fmt.Printf("DEBUG: Sending start byte and length of %d bytes\n", block)
}
tx <- startByte
blockNum := byte(block % 256)
tx <- blockNum
tx <- ^blockNum
//send data
var toSend bytes.Buffer
toSend.Write(data)
for padding := len(data); padding < packetPayloadLen; padding++ {
toSend.Write([]byte{asciiEOT})
}
if *xmodemTraceFlag {
fmt.Printf("DEBUG: Sending block: %d\n", block)
}
for sent := 0; sent < packetPayloadLen; sent++ {
if *xmodemTraceFlag {
fmt.Printf("DEBUG: Sending byte: %d of packet: %d\n", sent, block)
}
tx <- toSend.Bytes()[sent]
}
//calc CRC
u16CRC := crc16Constant(data, packetPayloadLen)
if *xmodemTraceFlag {
fmt.Println("DEBUG: Sending CRC")
}
//send CRC
tx <- byte(u16CRC >> 8)
tx <- byte(u16CRC & 0x0FF)
return nil
}
// XmodemSendShort transmits a file via XMODEM-CRC using the short (128-byte) packet length
func XmodemSendShort(rx chan byte, tx chan byte, f *os.File) error {
return xmodemSend(rx, tx, f, xmodemShortPacketLen)
}
// XmodemSendLong transmits a file via XMODEM-CRC using the long (1024-byte) packet length
func XmodemSendLong(rx chan byte, tx chan byte, f *os.File) error {
return xmodemSend(rx, tx, f, xmodemLongPacketLen)
}
func xmodemSend(rx chan byte, tx chan byte, f *os.File, packetPayloadLen int) error {
data, err := ioutil.ReadAll(f)
if err != nil {
return errors.New("XMODEM Could not read file to send")
}
if *xmodemTraceFlag {
fmt.Printf("XMODEM: Read %d bytes from file to transmit\n", len(data))
}
// oBuffer := make([]byte, 1)
if *xmodemTraceFlag {
fmt.Println("XMODEM: Waiting for POLL")
}
select {
case rb := <-rx:
switch rb {
case xmodemPOLL:
if *xmodemTraceFlag {
fmt.Println("XMODEM: Got POLL")
}
var blocks = len(data) / packetPayloadLen
if len(data) > blocks*packetPayloadLen {
blocks++
}
if *xmodemTraceFlag {
fmt.Printf("XMODEM: Total blocks to send: %d\n", blocks)
}
failed := 0
var currentBlock = 0
for currentBlock < blocks && failed < 10 {
sendBlock(tx, currentBlock+1, data[currentBlock*packetPayloadLen:(currentBlock+1)*packetPayloadLen], packetPayloadLen)
if *xmodemTraceFlag {
fmt.Println("XMODEM: sendBlock complete, waiting for response...")
}
select {
case resp := <-rx:
switch resp {
case asciiACK:
currentBlock++
if *xmodemTraceFlag {
fmt.Printf("XMODEM: Block: %d ACKed\n", currentBlock)
}
failed = 0
case asciiNAK:
failed++
if *xmodemTraceFlag {
fmt.Printf("XMODEM: Block: %d NAKed\n", currentBlock)
}
default:
fmt.Printf("XMODEM: Unexpected response to packet, got: 0x%x\n", resp)
return errors.New("XMODEM: Unexpected response to packet")
}
case <-time.After(ackTimeoutSecs * time.Second):
return errors.New("XMODEM: Send Failed - timeout waiting for ACX")
}
}
if failed == 10 {
return errors.New("XMODEM: Send failed - too many retries")
}
tx <- asciiEOT
default:
fmt.Printf("XMODEM: Got 0x%x instead of POLL character\n", rb)
return errors.New("XMODEM: Got unexpected response to file transfer - check settings")
}
case <-time.After(pollTimeoutSecs * time.Second):
return errors.New("XMODEM: Send Failed - timeout waiting for POLL")
}
return nil
}
// XModemReceive received a file using the XMODEM-CRC protocol
// in either 128 or 1024-byte packets as determined by the sender.
func XModemReceive(rx chan byte, tx chan byte) ([]byte, error) {
var (
data bytes.Buffer
packetSize int
crc uint16
)
if *xmodemTraceFlag {
fmt.Println("XMODEM: Sending POLL")
}
// Start Connection
tx <- xmodemPOLL
// Read Packets
done := false
for !done {
select {
case pType := <-rx:
if *xmodemTraceFlag {
fmt.Printf("XMODEM: Packet Type: 0x%x\t", pType)
}
switch pType {
case asciiEOT:
tx <- asciiACK
done = true
if *xmodemTraceFlag {
fmt.Println("Got EOT, done.")
}
continue
case asciiSOH:
packetSize = xmodemShortPacketLen
case asciiSTX:
packetSize = xmodemLongPacketLen
case asciiCAN:
return nil, errors.New("XMODEM: Transfer Cancelled by Sender")
default:
return nil, errors.New("XMODEM: Protocol Error")
}
packetCount := <-rx
if *xmodemTraceFlag {
fmt.Printf("Block: %d, Size: %d\t", packetCount, packetSize)
}
inverseCount := <-rx
if ^packetCount != inverseCount {
tx <- asciiNAK
if *xmodemTraceFlag {
fmt.Println("XMODEM: NAK due to count error")
}
continue
}
received := 0
var pData bytes.Buffer
for received < packetSize {
pData.WriteByte(<-rx)
received++
}
crc = uint16(<-rx)
crc <<= 8
crc |= uint16(<-rx)
// Calculate CRC
crcCalc := crc16(pData.Bytes())
if crcCalc == crc {
data.Write(pData.Bytes())
if *xmodemTraceFlag {
fmt.Println("ACK")
}
tx <- asciiACK
} else {
tx <- asciiNAK
if *xmodemTraceFlag {
fmt.Println("NAK due to CRC error")
}
}
case <-time.After(dataTimeoutSecs * time.Second):
return nil, errors.New("XMODEM: Recieve Failed - data timeout")
}
}
blob := data.Bytes()
// remove any trailing EOF indicators (asciiSUBs)
for blob[len(blob)-1] == asciiSUB {
blob = blob[:len(blob)-1]
}
return blob, nil
}