forked from ideazxy/iso8583
-
Notifications
You must be signed in to change notification settings - Fork 1
/
message.go
282 lines (240 loc) · 5.58 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
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
package iso8583
import (
"encoding/hex"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
)
const (
TAG_FIELD string = "field"
TAG_ENCODE string = "encode"
TAG_LENGTH string = "length"
TagPlain string = "plain"
)
type fieldInfo struct {
Index int
Encode int
LenEncode int
Length int
Field Iso8583Type
}
// Message is structure for ISO 8583 message encode and decode
type Message struct {
Mti string
MtiEncode int
SecondBitmap bool
Data interface{}
BitmapEncode int
}
// NewMessage creates new Message structure
func NewMessage(mti string, data interface{}) *Message {
return &Message{
Mti: mti,
MtiEncode: ASCII,
SecondBitmap: false,
Data: data,
}
}
// Bytes marshall Message to bytes
func (m *Message) Bytes() (ret []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New("Critical error:" + fmt.Sprint(r))
ret = nil
}
}()
ret = make([]byte, 0)
// generate MTI:
mtiBytes, err := m.encodeMti()
if err != nil {
return nil, err
}
ret = append(ret, mtiBytes...)
// generate bitmap and fields:
fields := parseFields(m.Data)
byteNum := 8
if m.SecondBitmap {
byteNum = 16
}
bitmap := make([]byte, byteNum)
data := make([]byte, 0, 512)
for byteIndex := 0; byteIndex < byteNum; byteIndex++ {
for bitIndex := 0; bitIndex < 8; bitIndex++ {
i := byteIndex*8 + bitIndex + 1
// if we need second bitmap (additional 8 bytes) - set first bit in first bitmap
if m.SecondBitmap && i == 1 {
step := uint(7 - bitIndex)
bitmap[byteIndex] |= (0x01 << step)
}
if info, ok := fields[i]; ok {
// if field is empty, then we can't add it to bitmap
if info.Field.IsEmpty() {
continue
}
// mark 1 in bitmap:
step := uint(7 - bitIndex)
bitmap[byteIndex] |= (0x01 << step)
// append data:
d, err := info.Field.Bytes(info.Encode, info.LenEncode, info.Length)
if err != nil {
return nil, err
}
data = append(data, d...)
}
}
}
if m.BitmapEncode == HexEncoding {
bitmap = []byte(strings.ToUpper(hex.EncodeToString(bitmap[:])))
}
ret = append(ret, bitmap...)
ret = append(ret, data...)
return ret, nil
}
func (m *Message) encodeMti() ([]byte, error) {
if m.Mti == "" {
return nil, errors.New("MTI is required")
}
if len(m.Mti) != 4 {
return nil, errors.New("MTI is invalid")
}
// check MTI, it must contain only digits
if _, err := strconv.Atoi(m.Mti); err != nil {
return nil, errors.New("MTI is invalid")
}
switch m.MtiEncode {
case BCD:
return bcd([]byte(m.Mti)), nil
default:
return []byte(m.Mti), nil
}
}
func parseFields(msg interface{}) map[int]*fieldInfo {
fields := make(map[int]*fieldInfo)
v := reflect.Indirect(reflect.ValueOf(msg))
if v.Kind() != reflect.Struct {
panic("data must be a struct")
}
for i := 0; i < v.NumField(); i++ {
if isPtrOrInterface(v.Field(i).Kind()) && v.Field(i).IsNil() {
continue
}
sf := v.Type().Field(i)
if sf.Tag == "" || sf.Tag.Get(TAG_FIELD) == "" {
continue
}
index, err := strconv.Atoi(sf.Tag.Get(TAG_FIELD))
if err != nil {
panic("value of field must be numeric")
}
encode := 0
lenEncode := 0
if raw := sf.Tag.Get(TAG_ENCODE); raw != "" {
enc := strings.Split(raw, ",")
if len(enc) == 2 {
lenEncode = parseEncodeStr(enc[0])
encode = parseEncodeStr(enc[1])
} else {
encode = parseEncodeStr(enc[0])
}
}
length := -1
if l := sf.Tag.Get(TAG_LENGTH); l != "" {
length, err = strconv.Atoi(l)
if err != nil {
panic("value of length must be numeric")
}
}
field, ok := v.Field(i).Interface().(Iso8583Type)
if !ok {
panic("field must be Iso8583Type")
}
fields[index] = &fieldInfo{index, encode, lenEncode, length, field}
}
return fields
}
func isPtrOrInterface(k reflect.Kind) bool {
return k == reflect.Interface || k == reflect.Ptr
}
func parseEncodeStr(str string) int {
switch str {
case "ascii":
return ASCII
case "lbcd":
fallthrough
case "bcd":
return BCD
case "rbcd":
return rBCD
}
return -1
}
// Load unmarshall Message from bytes
func (m *Message) Load(raw []byte) (err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New("Critical error:" + fmt.Sprint(r))
}
}()
if m.Mti == "" {
m.Mti, err = decodeMti(raw, m.MtiEncode)
if err != nil {
return err
}
}
start := 4
if m.MtiEncode == BCD {
start = 2
}
fields := parseFields(m.Data)
byteNum := 8
if raw[start]&0x80 == 0x80 {
// 1st bit == 1
m.SecondBitmap = true
byteNum = 16
}
// handle hexa
var bitByte []byte
if m.BitmapEncode == HexEncoding {
tempByte, err := hex.DecodeString(string(raw[start : start+byteNum*2]))
if err != nil {
return errors.New("cannot decode , not ascii format")
}
if tempByte[0]&0x80 == 0x80 {
m.SecondBitmap = true
byteNum = 16
}
bitByte, err = hex.DecodeString(string(raw[start : start+byteNum*2]))
if err != nil {
return errors.New("cannot decode , not ascii format")
}
start += byteNum * 2
} else {
bitByte = raw[start : start+byteNum]
start += byteNum
}
for byteIndex := 0; byteIndex < byteNum; byteIndex++ {
for bitIndex := 0; bitIndex < 8; bitIndex++ {
step := uint(7 - bitIndex)
if (bitByte[byteIndex] & (0x01 << step)) == 0 {
continue
}
i := byteIndex*8 + bitIndex + 1
if i == 1 {
// field 1 is the second bitmap
continue
}
f, ok := fields[i]
if !ok {
return fmt.Errorf("field %d not defined", i)
}
l, err := f.Field.Load(raw[start:], f.Encode, f.LenEncode, f.Length)
if err != nil {
return fmt.Errorf("field %d: %s", i, err)
}
start += l
}
}
return nil
}