-
Notifications
You must be signed in to change notification settings - Fork 12
/
dialog.go
726 lines (660 loc) · 21.5 KB
/
dialog.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
package dialog
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"net"
"strconv"
"strings"
"time"
"github.com/mitch000001/go-hbci/domain"
"github.com/mitch000001/go-hbci/element"
"github.com/mitch000001/go-hbci/internal"
"github.com/mitch000001/go-hbci/message"
"github.com/mitch000001/go-hbci/segment"
"github.com/mitch000001/go-hbci/transport"
)
// Dialog represents the common interface to use when talking to bank institutes
type Dialog interface {
SyncClientSystemID() (string, error)
SendMessage(message.HBCIMessage) (message.BankMessage, error)
}
const (
initialDialogID = "0"
initialClientSystemID = "0"
initialBankParameterDataVersion = 0
initialUserParameterDataVersion = 0
anonymousClientID = "9999999999"
)
func newDialog(
bankID domain.BankID,
hbciURL string,
userID string,
hbciVersion segment.HBCIVersion,
productName string,
productVersion string,
signatureProvider message.SignatureProvider,
cryptoProvider message.CryptoProvider,
) *dialog {
return &dialog{
hbciURL: hbciURL,
BankID: bankID,
UserID: userID,
clientID: userID,
ClientSystemID: initialClientSystemID,
Language: domain.German,
Accounts: make([]domain.AccountInformation, 0),
signatureProvider: signatureProvider,
cryptoProvider: cryptoProvider,
dialogID: initialDialogID,
hbciVersion: hbciVersion,
productName: productName,
productVersion: productVersion,
}
}
type dialog struct {
transport transport.Transport
hbciURL string
BankID domain.BankID
UserID string
clientID string
ClientSystemID string
Language domain.Language
UserParameterData domain.UserParameterData
Accounts []domain.AccountInformation
messageCount int
dialogID string
securityFn string
signatureProvider message.SignatureProvider
cryptoProvider message.CryptoProvider
BankParameterData BankParameterData
hbciVersion segment.HBCIVersion
productName string
productVersion string
supportedSegments []segment.VersionedSegment
}
func (d *dialog) UserParameterDataVersion() int {
return d.UserParameterData.Version
}
func (d *dialog) BankParameterDataVersion() int {
return d.BankParameterData.Version
}
func (d *dialog) SupportedSegments() []segment.VersionedSegment {
return d.supportedSegments
}
func (d *dialog) SetClientSystemID(clientSystemID string) {
d.ClientSystemID = clientSystemID
d.signatureProvider.SetClientSystemID(d.ClientSystemID)
d.cryptoProvider.SetClientSystemID(d.ClientSystemID)
}
func (d *dialog) SetSecurityFunction(securityFn string) {
d.securityFn = securityFn
d.signatureProvider.SetSecurityFunction(d.securityFn)
d.cryptoProvider.SetSecurityFunction(d.securityFn)
}
func (d *dialog) SendMessage(clientMessage message.HBCIMessage) (message.BankMessage, error) {
err := d.init()
if err != nil {
return nil, err
}
defer func() { logErr(d.end()) }()
requestMessage := d.newBasicMessage(clientMessage)
signedMessage, err := requestMessage.Sign(d.signatureProvider)
if err != nil {
return nil, err
}
encMessage, err := signedMessage.Encrypt(d.cryptoProvider)
if err != nil {
return nil, err
}
decryptedMessage, err := d.request(encMessage)
if err != nil {
return nil, err
}
var errors []string
acknowledgements := decryptedMessage.Acknowledgements()
for _, ack := range acknowledgements {
if ack.IsWarning() {
internal.Info.Printf("%v\n", ack)
}
if ack.IsError() {
errors = append(errors, ack.String())
}
}
if len(errors) > 0 {
return nil, fmt.Errorf("institute returned errors:\n%s", strings.Join(errors, "\n"))
}
return decryptedMessage, nil
}
func (d *dialog) SyncUserParameterData() error {
internal.Info.Printf("Initializing dialog")
err := d.init()
if err != nil {
return err
}
defer func() {
internal.Info.Printf("Ending dialog")
logErr(d.end())
}()
return nil
}
func (d *dialog) SyncClientSystemID() (string, error) {
syncMessage := message.NewSynchronisationMessage(d.hbciVersion)
syncMessage.Identification = segment.NewIdentificationSegment(d.BankID, d.clientID, initialClientSystemID, true)
syncMessage.ProcessingPreparation = segment.NewProcessingPreparationSegmentV3(
initialBankParameterDataVersion, initialUserParameterDataVersion, domain.German, d.productName, d.productVersion,
)
syncMessage.TanRequest = d.hbciVersion.TanProcess4Request(segment.IdentificationID)
syncMessage.Sync = d.hbciVersion.SynchronisationRequest(segment.SyncModeAquireClientID)
syncMessage.BasicMessage = d.newBasicMessage(syncMessage)
signedSyncMessage, err := syncMessage.Sign(d.signatureProvider)
if err != nil {
return "", err
}
d.cryptoProvider.SetClientSystemID(initialClientSystemID)
encryptedSyncMessage, err := signedSyncMessage.Encrypt(d.cryptoProvider)
if err != nil {
return "", err
}
decryptedMessage, err := d.request(encryptedSyncMessage)
if err != nil {
return "", fmt.Errorf("error while extracting encrypted message: %v", err)
}
messageHeader := decryptedMessage.MessageHeader()
if messageHeader == nil {
return "", fmt.Errorf("malformed response message: %q", decryptedMessage)
}
d.dialogID = messageHeader.DialogID.Val()
var errors []string
acknowledgements := decryptedMessage.Acknowledgements()
for _, ack := range acknowledgements {
if ack.IsSuccess() {
internal.Debug.Printf("%v\n", ack)
}
if ack.IsWarning() {
internal.Info.Printf("%v\n", ack)
}
if ack.IsError() {
errors = append(errors, ack.String())
}
}
if len(errors) > 0 {
return "", fmt.Errorf("institute returned errors:\n%s", strings.Join(errors, "\n"))
}
if err := d.updateSecurityFunctionIfNeeded(decryptedMessage); err != nil {
return "", fmt.Errorf("error updating security function: %w", err)
}
syncResponse := decryptedMessage.FindSegment("HISYN")
if syncResponse != nil {
syncSegment := syncResponse.(segment.SynchronisationResponse)
d.SetClientSystemID(syncSegment.ClientSystemID())
} else {
return "", fmt.Errorf("malformed message: missing unmarshaler for SynchronisationResponse")
}
err = d.parseBankParameterData(decryptedMessage)
if err != nil {
return "", err
}
err = d.parseUserParameterData(decryptedMessage)
if err != nil {
return "", err
}
err = d.end()
if err != nil {
return "", err
}
return d.ClientSystemID, nil
}
func (d *dialog) SendAnonymousMessage(clientMessage message.HBCIMessage) (message.BankMessage, error) {
err := d.anonymousInit()
if err != nil {
return nil, fmt.Errorf("Error while initating anonymous dialog: %v", err)
}
defer func() { logErr(d.anonymousEnd()) }()
// TODO: add checks if job needs signature or not
requestMessage := d.newBasicMessage(clientMessage)
requestMessage.SetSegmentPositions()
bankMessage, err := d.request(requestMessage)
if err != nil {
return nil, err
}
var errors []string
acknowledgements := bankMessage.Acknowledgements()
for _, ack := range acknowledgements {
if ack.IsWarning() {
fmt.Printf("%v\n", ack)
}
if ack.IsError() {
errors = append(errors, ack.String())
}
}
if len(errors) > 0 {
return nil, fmt.Errorf("Institute returned errors:\n%s", strings.Join(errors, "\n"))
}
return bankMessage, nil
}
func (d *dialog) anonymousInit() error {
d.dialogID = initialDialogID
d.messageCount = 0
initMessage := message.NewDialogInitializationClientMessage(d.hbciVersion)
initMessage.Identification = segment.NewIdentificationSegment(d.BankID, anonymousClientID, initialClientSystemID, false)
initMessage.ProcessingPreparation = segment.NewProcessingPreparationSegmentV3(
d.BankParameterDataVersion(), d.UserParameterDataVersion(), d.Language, d.productName, d.productVersion,
)
initMessage.BasicMessage = d.newBasicMessage(initMessage)
initMessage.SetSegmentPositions()
bankMessage, err := d.request(initMessage)
if err != nil {
return err
}
messageHeader := bankMessage.MessageHeader()
if messageHeader == nil {
return fmt.Errorf("malformed response message: %q", bankMessage)
}
d.dialogID = messageHeader.DialogID.Val()
err = d.parseBankParameterData(bankMessage)
if err != nil {
return err
}
err = d.parseUserParameterData(bankMessage)
if err != nil {
return err
}
bankInfoMessage := bankMessage.FindSegment(segment.BankAnnouncementID)
if bankInfoMessage != nil {
bankInfoSegment := bankInfoMessage.(*segment.BankAnnouncementSegment)
internal.Info.Printf("INFO:\n%s\n%s\n", bankInfoSegment.Subject.Val(), bankInfoSegment.Body.Val())
}
errors := make([]string, 0)
acknowledgements := bankMessage.Acknowledgements()
for _, ack := range acknowledgements {
if ack.IsWarning() {
fmt.Printf("%v\n", ack)
}
if ack.IsError() {
errors = append(errors, ack.String())
}
}
if len(errors) > 0 {
return fmt.Errorf("DialogEnd: Institute returned errors:\n%s", strings.Join(errors, "\n"))
}
return nil
}
func (d *dialog) anonymousEnd() error {
dialogEnd := message.NewDialogFinishingMessage(d.hbciVersion, d.dialogID)
dialogEnd.BasicMessage = d.newBasicMessage(dialogEnd)
dialogEnd.SetSegmentPositions()
decryptedMessage, err := d.request(dialogEnd)
if err != nil {
return fmt.Errorf("Error while ending dialog: %v", err)
}
errors := make([]string, 0)
acknowledgements := decryptedMessage.Acknowledgements()
for _, ack := range acknowledgements {
if ack.IsError() {
errors = append(errors, ack.String())
}
}
if len(errors) > 0 {
return fmt.Errorf("DialogEnd: Institute returned errors:\n%s", strings.Join(errors, "\n"))
}
return nil
}
func (d *dialog) init() error {
if d.ClientSystemID == initialClientSystemID {
id, err := d.SyncClientSystemID()
if err != nil {
return err
}
d.ClientSystemID = id
}
d.dialogID = initialDialogID
d.messageCount = 0
initMessage := message.NewDialogInitializationClientMessage(d.hbciVersion)
initMessage.Identification = segment.NewIdentificationSegment(d.BankID, d.clientID, d.ClientSystemID, true)
initMessage.ProcessingPreparation = segment.NewProcessingPreparationSegmentV3(
d.BankParameterDataVersion(), d.UserParameterDataVersion(), d.Language, d.productName, d.productVersion,
)
initMessage.TanRequest = d.hbciVersion.TanProcess4Request(segment.IdentificationID)
initMessage.BasicMessage = d.newBasicMessage(initMessage)
signedInitMessage, err := initMessage.Sign(d.signatureProvider)
if err != nil {
return err
}
encryptedInitMessage, err := signedInitMessage.Encrypt(d.cryptoProvider)
if err != nil {
return err
}
decryptedMessage, err := d.request(encryptedInitMessage)
if err != nil {
return fmt.Errorf("error while initializing dialog: %v", err)
}
messageHeader := decryptedMessage.MessageHeader()
if messageHeader == nil {
return fmt.Errorf("malformed response message: %q", decryptedMessage)
}
d.dialogID = messageHeader.DialogID.Val()
err = d.parseBankParameterData(decryptedMessage)
if err != nil {
return err
}
err = d.parseUserParameterData(decryptedMessage)
if err != nil {
return err
}
bankInfoMessage := decryptedMessage.FindSegment(segment.BankAnnouncementID)
if bankInfoMessage != nil {
bankInfoSegment := bankInfoMessage.(*segment.BankAnnouncementSegment)
internal.Info.Printf("INFO:\n%s\n%s\n", bankInfoSegment.Subject.Val(), bankInfoSegment.Body.Val())
}
var errors []string
acknowledgements := decryptedMessage.Acknowledgements()
for _, ack := range acknowledgements {
if ack.IsSuccess() {
internal.Debug.Printf("%v\n", ack)
}
if ack.IsWarning() {
internal.Info.Printf("%v\n", ack)
}
if ack.IsError() {
errors = append(errors, ack.String())
}
}
if len(errors) > 0 {
return fmt.Errorf("DialogEnd: Institute returned errors:\n%s", strings.Join(errors, "\n"))
}
if err := d.updateSecurityFunctionIfNeeded(decryptedMessage); err != nil {
return fmt.Errorf("error updating security function: %w", err)
}
return nil
}
func (d *dialog) end() error {
dialogEnd := message.NewDialogFinishingMessage(d.hbciVersion, d.dialogID)
dialogEnd.BasicMessage = d.newBasicMessage(dialogEnd)
signedDialogEnd, err := dialogEnd.Sign(d.signatureProvider)
if err != nil {
return err
}
encryptedDialogEnd, err := signedDialogEnd.Encrypt(d.cryptoProvider)
if err != nil {
return err
}
decryptedMessage, err := d.request(encryptedDialogEnd)
if err != nil {
return fmt.Errorf("Error while ending dialog: %v", err)
}
errors := make([]string, 0)
acknowledgements := decryptedMessage.Acknowledgements()
for _, ack := range acknowledgements {
if ack.IsError() {
errors = append(errors, ack.String())
}
}
if len(errors) > 0 {
return fmt.Errorf("DialogEnd: Institute returned errors:\n%s", strings.Join(errors, "\n"))
}
return nil
}
func (d *dialog) newClientMessage(hbciMessage message.HBCIMessage) message.ClientMessage {
return d.newBasicMessage(hbciMessage)
}
func (d *dialog) newBasicMessage(hbciMessage message.HBCIMessage) *message.BasicMessage {
messageNum := d.nextMessageNumber()
clientMessage := message.NewBasicMessage(hbciMessage)
clientMessage.Header = segment.NewMessageHeaderSegment(-1, d.hbciVersion.Version(), d.dialogID, messageNum)
clientMessage.End = segment.NewMessageEndSegment(-1, messageNum)
return clientMessage
}
func (d *dialog) updateSecurityFunctionIfNeeded(message message.BankMessage) error {
if !d.hasSupportedSecurityAcknowledgement(message) {
return nil
}
supportedSecurityFns, ok := d.supportedSecurityFunctionsFromBankMessage(message)
if !ok {
return fmt.Errorf("no supported security function implemented")
}
oldSecurityFn := d.securityFn
newSecurityFn := ""
newSecurityFnName := ""
// TODO: proper handling of each case, see FINTS3.0 docu -> Ask user which to use
for fn, name := range supportedSecurityFns {
newSecurityFn = fn
newSecurityFnName = name
break
}
if oldSecurityFn != newSecurityFn {
internal.Info.Printf(
"New supported security function found. Setting new security function %q (%s).", newSecurityFnName, newSecurityFn,
)
d.SetSecurityFunction(newSecurityFn)
}
return nil
}
func (d *dialog) hasSupportedSecurityAcknowledgement(message message.BankMessage) bool {
rawTanBPDSegment := message.FindSegment(segment.TanBankParameterID)
if rawTanBPDSegment == nil {
return false
}
for _, ack := range message.Acknowledgements() {
if ack.Code == element.AcknowledgementSupportedSecurityFunction {
return true
}
}
return false
}
func (d *dialog) supportedSecurityFunctionsFromBankMessage(message message.BankMessage) (map[string]string, bool) {
acknowledgements := message.Acknowledgements()
var supportedSecurityFns []string
for _, ack := range acknowledgements {
if ack.Code == element.AcknowledgementSupportedSecurityFunction {
supportedSecurityFns = ack.Params
break
}
}
if len(supportedSecurityFns) == 0 {
return nil, false
}
securityFunctions := map[string]string{}
rawSegment := message.FindSegment(segment.TanBankParameterID)
if rawSegment == nil {
return nil, false
}
availableSecurityFns := map[string]*element.Tan2StepSubmissionProcessParameterV6{}
for _, pp := range rawSegment.(*segment.TanBankParameterV6).Tan2StepSubmissionParameter.ProcessParameters.GroupDataElements() {
tan2StepPP := pp.(*element.Tan2StepSubmissionProcessParameterV6)
fn := tan2StepPP.SecurityFunction.Val()
availableSecurityFns[fn] = tan2StepPP
}
for _, sf := range supportedSecurityFns {
if pp, ok := availableSecurityFns[sf]; ok {
securityFunctions[sf] = pp.TwoStepProcessName.Val()
}
}
if len(securityFunctions) == 0 {
return nil, false
}
return securityFunctions, true
}
func (d *dialog) parseBankParameterData(bankMessage message.BankMessage) error {
bankParamData := bankMessage.FindSegment(segment.CommonBankParameterID)
if bankParamData == nil {
return nil
}
paramSegment, ok := bankParamData.(segment.CommonBankParameter)
if !ok {
return fmt.Errorf("error converting common bank parameter data")
}
d.supportedSegments = bankMessage.SupportedSegments()
d.BankParameterData = BankParameterData{
BankParameterData: paramSegment.BankParameterData(),
SupportedSegmentParameters: make([]SegmentParameter, len(d.supportedSegments)),
}
pinTanTransactions := bankMessage.FindSegment(segment.PinTanBankParameterID)
if pinTanTransactions != nil {
pinTanTransactionSegment := pinTanTransactions.(segment.PinTanBusinessTransactionParams)
pinTransactions := make(map[string]bool)
for _, transaction := range pinTanTransactionSegment.PinTanBusinessTransactions() {
pinTransactions[transaction.SegmentID] = transaction.NeedsTan
}
d.BankParameterData.PinTanBusinessTransactions = pinTransactions
}
for i, s := range d.supportedSegments {
param := SegmentParameter{
VersionedSegment: s,
}
parameterData := bankMessage.FindSegment(s.ID)
if parameterData != nil && parameterData.Header().Version.Val() == s.Version {
param.Parameters = parameterData
}
d.BankParameterData.SupportedSegmentParameters[i] = param
}
return nil
}
func (d *dialog) parseUserParameterData(bankMessage message.BankMessage) error {
userParamData := bankMessage.FindSegment(segment.CommonUserParameterDataID)
if userParamData != nil {
paramSegment := userParamData.(segment.CommonUserParameterData)
d.UserParameterData = paramSegment.UserParameterData()
d.clientID = d.UserParameterData.UserID
}
accountData := bankMessage.FindSegments(segment.AccountInformationID)
for _, acc := range accountData {
infoSegment := acc.(segment.AccountInformation)
d.Accounts = append(d.Accounts, infoSegment.Account())
}
return nil
}
func (d *dialog) request(clientMessage message.ClientMessage) (message.BankMessage, error) {
marshaledMessage, err := clientMessage.MarshalHBCI()
if err != nil {
return nil, err
}
internal.Debug.Printf("Request:\n")
for _, seg := range bytes.Split(marshaledMessage, []byte("'")) {
internal.Debug.Printf("%q\n", seg)
}
reqBody := bytes.NewReader(marshaledMessage)
request := &transport.Request{
URL: d.hbciURL,
Body: io.NopCloser(reqBody),
}
response, err := d.transport.Do(request)
if err != nil {
return nil, fmt.Errorf("error executing Transport request: %v", err)
}
response, err = transport.ReadResponse(bufio.NewReader(response.Body), response.Request)
if err != nil {
return nil, fmt.Errorf("error reading response from Transport: %v", err)
}
var bankMessage message.BankMessage
if response.IsEncrypted() {
encMessage, err := d.extractEncryptedMessage(response)
if err != nil {
return nil, err
}
decryptedMessage, err := encMessage.Decrypt(d.cryptoProvider)
if err != nil {
return nil, fmt.Errorf("error while decrypting message: %v", err)
}
internal.Debug.Printf("Response:\n %s\n", decryptedMessage.MessageHeader())
bankMessage = decryptedMessage
} else {
decryptedMessage, err := extractUnencryptedMessage(response)
if err != nil {
return nil, err
}
internal.Debug.Printf("Response:\n %s\n", decryptedMessage.MessageHeader())
bankMessage = decryptedMessage
}
return bankMessage, err
}
func (d *dialog) extractEncryptedMessage(response *transport.Response) (*message.EncryptedMessage, error) {
messageHeader := response.FindSegment(segment.MessageHeaderID)
if messageHeader == nil {
return nil, fmt.Errorf("malformed response: missing Message Header")
}
header := &segment.MessageHeaderSegment{}
err := header.UnmarshalHBCI(messageHeader)
if err != nil {
return nil, fmt.Errorf("error while unmarshaling message header: %v", err)
}
// TODO: parse messageEnd
// TODO: parse encryptionHeader
encMessage := message.NewEncryptedMessage(header, nil, d.hbciVersion)
encryptedData := response.FindSegment("HNVSD")
if encryptedData != nil {
encSegment := &segment.EncryptedDataSegment{}
err = encSegment.UnmarshalHBCI(encryptedData)
if err != nil {
return nil, fmt.Errorf("error while unmarshaling encrypted data: %v", err)
}
encMessage.EncryptedData = encSegment
} else {
return nil, fmt.Errorf("malformed response: missing encrypted data: \n%v", response)
}
return encMessage, nil
}
func extractUnencryptedMessage(response *transport.Response) (message.BankMessage, error) {
messageHeader := response.FindSegment(segment.MessageHeaderID)
if messageHeader == nil {
return nil, fmt.Errorf("malformed response: missing Message Header")
}
header := &segment.MessageHeaderSegment{}
err := header.UnmarshalHBCI(messageHeader)
if err != nil {
return nil, fmt.Errorf("Error while unmarshaling message header: %v", err)
}
// TODO: parse messageEnd
decryptedMessage, err := message.NewDecryptedMessage(header, nil, response.MarshaledResponse)
if err != nil {
return nil, fmt.Errorf("error while unmarshaling unencrypted data: %v", err)
}
return decryptedMessage, nil
}
func (d *dialog) nextMessageNumber() int {
d.messageCount++
return d.messageCount
}
func (d *dialog) dial(message []byte) ([]byte, error) {
conn, err := net.Dial("tcp4", d.hbciURL)
if err != nil {
return nil, err
}
defer func() { logErr(conn.Close()) }()
err = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
if err != nil {
return nil, err
}
fmt.Fprintf(conn, "%s\r\n\r\n", string(message))
buf := bufio.NewReader(conn)
// read answer header
header, err := buf.ReadString('\'')
if err != nil {
return nil, err
}
headerItems := strings.Split(header, "+")
if len(headerItems) < 2 {
return nil, fmt.Errorf("response header too short")
}
sizeString := headerItems[1]
size, err := strconv.Atoi(sizeString)
if err != nil {
return nil, fmt.Errorf("error while parsing message size: %T:%v", err, err)
}
messageBuf := make([]byte, size)
_, err = buf.Read(messageBuf)
if err != nil {
return nil, fmt.Errorf("error while reading message: %T:%v", err, err)
}
var retBuf bytes.Buffer
retBuf.WriteString(header)
retBuf.Write(messageBuf)
return retBuf.Bytes(), err
}
func logErr(err error) {
if err != nil {
log.Println(err)
}
}