forked from sijms/go-ora
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
executable file
·1415 lines (1361 loc) · 34.7 KB
/
session.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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package network
import (
"bytes"
"context"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"encoding/pem"
"errors"
"fmt"
"github.com/sijms/go-ora/trace"
"net"
"reflect"
"strings"
"time"
"github.com/sijms/go-ora/converters"
)
type Data interface {
Write(session *Session) error
Read(session *Session) error
}
type SessionState struct {
summary *SummaryObject
sendPcks []PacketInterface
InBuffer []byte
OutBuffer bytes.Buffer
index int
}
type Session struct {
ctx context.Context
oldCtx context.Context
conn net.Conn
sslConn *tls.Conn
//connOption ConnectionOption
Context *SessionContext
sendPcks []PacketInterface
inBuffer []byte
outBuffer bytes.Buffer
index int
key []byte
salt []byte
verifierType int
TimeZone []byte
TTCVersion uint8
HasEOSCapability bool
HasFSAPCapability bool
Summary *SummaryObject
states []SessionState
StrConv converters.IStringConverter
UseBigClrChunks bool
UseBigScn bool
ClrChunkSize int
SSL struct {
CertificateRequest []*x509.CertificateRequest
PrivateKeys []*rsa.PrivateKey
Certificates []*x509.Certificate
roots *x509.CertPool
tlsCertificates []tls.Certificate
}
//certificates []*x509.Certificate
}
func NewSessionWithInputBufferForDebug(input []byte) *Session {
options := &ConnectionOption{
AdvNegoSeviceInfo: AdvNegoSeviceInfo{AuthService: nil},
SessionInfo: SessionInfo{
SessionDataUnitSize: 0xFFFF,
TransportDataUnitSize: 0xFFFF,
},
Tracer: trace.NilTracer(),
}
return &Session{
ctx: context.Background(),
conn: nil,
inBuffer: input,
index: 0,
//connOption: *connOption,
Context: NewSessionContext(options),
Summary: nil,
UseBigClrChunks: false,
ClrChunkSize: 0x40,
}
}
func NewSession(connOption *ConnectionOption) *Session {
return &Session{
ctx: context.Background(),
conn: nil,
inBuffer: nil,
index: 0,
//connOption: *connOption,
Context: NewSessionContext(connOption),
Summary: nil,
UseBigClrChunks: false,
ClrChunkSize: 0x40,
}
}
// SaveState save current session state and accept new state
// if new state is nil the session will be resetted
func (session *Session) SaveState(newState *SessionState) {
session.states = append(session.states, SessionState{
summary: session.Summary,
sendPcks: session.sendPcks,
InBuffer: session.inBuffer,
OutBuffer: session.outBuffer,
index: session.index,
})
if newState == nil {
session.Summary = nil
session.sendPcks = nil
session.inBuffer = nil
session.outBuffer = bytes.Buffer{}
session.index = 0
} else {
session.Summary = newState.summary
session.sendPcks = newState.sendPcks
session.inBuffer = newState.InBuffer
session.outBuffer = newState.OutBuffer
session.index = newState.index
}
}
// LoadState load last saved session state and return the current state
// if this is the only session state available set session state memory to nil
func (session *Session) LoadState() (oldState *SessionState) {
index := len(session.states) - 1
if index >= 0 {
oldState = &session.states[index]
}
if index >= 0 {
currentState := session.states[index]
session.Summary = currentState.summary
session.sendPcks = currentState.sendPcks
session.inBuffer = currentState.InBuffer
session.outBuffer = currentState.OutBuffer
session.index = currentState.index
if index == 0 {
session.states = nil
} else {
session.states = session.states[:index]
}
}
return
}
// ResetBuffer empty in and out buffer and set read index to 0
func (session *Session) ResetBuffer() {
session.Summary = nil
session.sendPcks = nil
session.inBuffer = nil
session.outBuffer.Reset()
session.index = 0
}
func (session *Session) StartContext(ctx context.Context) {
session.oldCtx = session.ctx
session.ctx = ctx
}
func (session *Session) EndContext() {
session.ctx = session.oldCtx
}
func (session *Session) initRead() error {
var err error
if deadline, ok := session.ctx.Deadline(); ok {
if session.sslConn != nil {
err = session.sslConn.SetReadDeadline(deadline)
} else {
err = session.conn.SetReadDeadline(deadline)
}
} else {
if session.sslConn != nil {
err = session.sslConn.SetReadDeadline(time.Time{})
} else {
err = session.conn.SetReadDeadline(time.Time{})
}
}
return err
}
func (session *Session) initWrite() error {
var err error
if deadline, ok := session.ctx.Deadline(); ok {
if session.sslConn != nil {
err = session.sslConn.SetWriteDeadline(deadline)
} else {
err = session.conn.SetWriteDeadline(deadline)
}
} else {
if session.sslConn != nil {
err = session.sslConn.SetWriteDeadline(time.Time{})
} else {
err = session.conn.SetWriteDeadline(time.Time{})
}
}
return err
}
// LoadSSLData load data required for SSL connection like certificate, private keys and
// certificate requests
func (session *Session) LoadSSLData(certs, keys, certRequests [][]byte) error {
for _, temp := range certs {
cert, err := x509.ParseCertificate(temp)
if err != nil {
return err
}
session.SSL.Certificates = append(session.SSL.Certificates, cert)
for _, temp2 := range keys {
key, err := x509.ParsePKCS1PrivateKey(temp2)
if err != nil {
return err
}
if key.PublicKey.Equal(cert.PublicKey) {
certPem := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: temp,
})
keyPem := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
})
tlsCert, err := tls.X509KeyPair(certPem, keyPem)
if err != nil {
return err
}
session.SSL.tlsCertificates = append(session.SSL.tlsCertificates, tlsCert)
}
}
}
for _, temp := range certRequests {
cert, err := x509.ParseCertificateRequest(temp)
if err != nil {
return err
}
session.SSL.CertificateRequest = append(session.SSL.CertificateRequest, cert)
}
return nil
}
// negotiate it is a step in SSL communication in which tcp connection is
// used to create sslConn object
func (session *Session) negotiate() {
connOption := session.Context.ConnOption
if session.SSL.roots == nil {
session.SSL.roots = x509.NewCertPool()
for _, cert := range session.SSL.Certificates {
session.SSL.roots.AddCert(cert)
}
}
host := connOption.GetActiveServer(false)
config := &tls.Config{
Certificates: session.SSL.tlsCertificates,
RootCAs: session.SSL.roots,
ServerName: host.Addr,
}
if !connOption.SSLVerify {
config.InsecureSkipVerify = true
}
session.sslConn = tls.Client(session.conn, config)
}
// Connect perform network connection on address:port
// check if the client need to use SSL
// then send connect packet to the server and
// receive either accept, redirect or refuse packet
func (session *Session) Connect(ctx context.Context) error {
session.StartContext(ctx)
defer session.EndContext()
connOption := session.Context.ConnOption
session.Disconnect()
connOption.Tracer.Print("Connect")
var err error
var connected = false
var host *ServerAddr
var loop = true
dialer := net.Dialer{
Timeout: time.Second * session.Context.ConnOption.Timeout,
}
for loop {
host = connOption.GetActiveServer(false)
if host == nil {
return errors.New("no available servers to connect to")
}
addr := host.networkAddr()
if len(session.Context.ConnOption.UnixAddress) > 0 {
session.conn, err = dialer.DialContext(ctx, "unix", session.Context.ConnOption.UnixAddress)
} else {
session.conn, err = dialer.DialContext(ctx, "tcp", addr)
}
if err != nil {
connOption.Tracer.Printf("using: %s ..... [FAILED]", addr)
host = connOption.GetActiveServer(true)
if host == nil {
break
}
continue
}
connOption.Tracer.Printf("using: %s ..... [SUCCEED]", addr)
connected = true
loop = false
}
if !connected {
return err
}
err = connOption.updateSSL(host)
if err != nil {
return err
}
if connOption.SSL {
connOption.Tracer.Print("Using SSL/TLS")
session.negotiate()
}
connOption.Tracer.Print("Open :", connOption.ConnectionData())
connectPacket := newConnectPacket(*session.Context)
err = session.writePacket(connectPacket)
if err != nil {
return err
}
if uint16(connectPacket.packet.length) == connectPacket.packet.dataOffset {
session.PutBytes(connectPacket.buffer...)
err = session.Write()
if err != nil {
return err
}
}
pck, err := session.readPacket()
if err != nil {
return err
}
if acceptPacket, ok := pck.(*AcceptPacket); ok {
*session.Context = acceptPacket.sessionCtx
session.Context.handshakeComplete = true
connOption.Tracer.Print("Handshake Complete")
return nil
}
if redirectPacket, ok := pck.(*RedirectPacket); ok {
connOption.Tracer.Print("Redirect")
//connOption.connData = redirectPacket.reconnectData
servers, err := extractServers(redirectPacket.redirectAddr)
if err != nil {
return err
}
for _, srv := range servers {
connOption.AddServer(srv)
}
host = connOption.GetActiveServer(true)
return session.Connect(ctx)
}
if refusePacket, ok := pck.(*RefusePacket); ok {
refusePacket.extractErrCode()
var addr string
var port int
if host != nil {
addr = host.Addr
port = host.Port
}
connOption.Tracer.Printf("connection to %s:%d refused with error: %s", addr, port, refusePacket.Err.Error())
host = connOption.GetActiveServer(true)
if port == 0 {
session.Disconnect()
return &refusePacket.Err
}
return session.Connect(ctx)
}
return errors.New("connection refused by the server due to unknown reason")
}
// Disconnect close the network and release resources
func (session *Session) Disconnect() {
session.ResetBuffer()
if session.sslConn != nil {
_ = session.sslConn.Close()
session.sslConn = nil
}
if session.conn != nil {
_ = session.conn.Close()
session.conn = nil
}
}
//func (session *Session) Debug() {
// //if session.index > 350 && session.index < 370 {
// fmt.Println("index: ", session.index)
// fmt.Printf("data buffer: %#v\n", session.InBuffer[session.index:session.index+30])
// //oldIndex := session.index
// //fmt.Println(session.GetClr())
// //session.index = oldIndex
// //}
//}
//func (session *Session) DumpIn() {
// log.Printf("%#v\n", session.InBuffer)
//}
//
//func (session *Session) DumpOut() {
// log.Printf("%#v\n", session.OutBuffer)
//}
// Write send data store in output buffer through network
//
// if data bigger than SessionDataUnit it should be divided into
// segment and each segment sent in data packet
func (session *Session) Write() error {
outputBytes := session.outBuffer.Bytes()
size := session.outBuffer.Len()
if size == 0 {
// send empty data packet
pck, err := newDataPacket(nil, session.Context)
if err != nil {
return err
}
return session.writePacket(pck)
//return errors.New("the output buffer is empty")
}
segmentLen := int(session.Context.SessionDataUnit - 20)
offset := 0
for size > segmentLen {
pck, err := newDataPacket(outputBytes[offset:offset+segmentLen], session.Context)
if err != nil {
return err
}
err = session.writePacket(pck)
if err != nil {
session.outBuffer.Reset()
return err
}
size -= segmentLen
offset += segmentLen
}
if size != 0 {
pck, err := newDataPacket(outputBytes[offset:], session.Context)
if err != nil {
return err
}
err = session.writePacket(pck)
if err != nil {
session.outBuffer.Reset()
return err
}
}
return nil
}
// Read numBytes of data from input buffer if requested data is larger
// than input buffer session will get the remaining from network stream
func (session *Session) read(numBytes int) ([]byte, error) {
if session.index+numBytes > len(session.inBuffer) {
pck, err := session.readPacket()
if err != nil {
return nil, err
}
if dataPck, ok := pck.(*DataPacket); ok {
session.inBuffer = append(session.inBuffer, dataPck.buffer...)
} else {
return nil, errors.New("the packet received is not data packet")
}
}
ret := session.inBuffer[session.index : session.index+numBytes]
session.index += numBytes
return ret, nil
}
// Write a packet to the network stream
func (session *Session) writePacket(pck PacketInterface) error {
session.sendPcks = append(session.sendPcks, pck)
tracer := session.Context.ConnOption.Tracer
tmp := pck.bytes()
tracer.LogPacket("Write packet:", tmp)
var err = session.initWrite()
if err != nil {
return err
}
if session.sslConn != nil {
_, err = session.sslConn.Write(tmp)
} else {
_, err = session.conn.Write(tmp)
}
return err
}
// HasError Check if the session has error or not
func (session *Session) HasError() bool {
return session.Summary != nil && session.Summary.RetCode != 0
}
// GetError Return the error in form or OracleError
func (session *Session) GetError() *OracleError {
err := &OracleError{}
if session.Summary != nil && session.Summary.RetCode != 0 {
err.ErrCode = session.Summary.RetCode
if session.StrConv != nil {
err.ErrMsg = session.StrConv.Decode(session.Summary.ErrorMessage)
} else {
err.ErrMsg = string(session.Summary.ErrorMessage)
}
}
return err
}
// read a packet from network stream
func (session *Session) readPacket() (PacketInterface, error) {
readPacketData := func() ([]byte, error) {
trials := 0
for {
if trials > 3 {
return nil, errors.New("abnormal response")
}
trials++
head := make([]byte, 8)
var err error
err = session.initRead()
if err != nil {
return nil, err
}
if session.sslConn != nil {
_, err = session.sslConn.Read(head)
} else {
_, err = session.conn.Read(head)
}
//_, err := conn.Read(head)
if err != nil {
return nil, err
}
pckType := PacketType(head[4])
var length uint32
if session.Context.handshakeComplete && session.Context.Version >= 315 {
length = binary.BigEndian.Uint32(head)
} else {
length = uint32(binary.BigEndian.Uint16(head))
}
length -= 8
body := make([]byte, length)
index := uint32(0)
for index < length {
var temp int
err = session.initRead()
if err != nil {
return nil, err
}
if session.sslConn != nil {
temp, err = session.sslConn.Read(body[index:])
} else {
temp, err = session.conn.Read(body[index:])
}
//temp, err := conn.Read(body[index:])
if err != nil {
if e, ok := err.(net.Error); ok && e.Timeout() && temp != 0 {
index += uint32(temp)
continue
}
return nil, err
}
index += uint32(temp)
}
if pckType == RESEND {
if session.Context.ConnOption.SSL {
session.negotiate()
}
for _, pck := range session.sendPcks {
//log.Printf("Request: %#v\n\n", pck.bytes())
err := session.initWrite()
if err != nil {
return nil, err
}
if session.Context.ConnOption.SSL {
_, err = session.sslConn.Write(pck.bytes())
} else {
_, err = session.conn.Write(pck.bytes())
}
if err != nil {
return nil, err
}
}
continue
}
ret := append(head, body...)
session.Context.ConnOption.Tracer.LogPacket("Read packet:", ret)
return ret, nil
}
}
var packetData []byte
var err error
packetData, err = readPacketData()
if err != nil {
return nil, err
}
pckType := PacketType(packetData[4])
//log.Printf("Response: %#v\n\n", packetData)
switch pckType {
case ACCEPT:
return newAcceptPacketFromData(packetData, session.Context.ConnOption), nil
case REFUSE:
return newRefusePacketFromData(packetData), nil
case REDIRECT:
pck := newRedirectPacketFromData(packetData)
dataLen := binary.BigEndian.Uint16(packetData[8:])
var data string
if uint16(pck.packet.length) <= pck.packet.dataOffset {
packetData, err = readPacketData()
dataPck, err := newDataPacketFromData(packetData, session.Context)
if err != nil {
return nil, err
}
data = string(dataPck.buffer)
} else {
data = string(packetData[10 : 10+dataLen])
}
//fmt.Println("data returned: ", data)
length := strings.Index(data, "\x00")
if pck.packet.flag&2 != 0 && length > 0 {
pck.redirectAddr = data[:length]
pck.reconnectData = data[length:]
} else {
pck.redirectAddr = data
}
return pck, nil
case DATA:
return newDataPacketFromData(packetData, session.Context)
case MARKER:
pck := newMarkerPacketFromData(packetData, session.Context)
breakConnection := false
resetConnection := false
switch pck.markerType {
case 0:
breakConnection = true
case 1:
if pck.markerData == 2 {
resetConnection = true
} else {
breakConnection = true
}
default:
return nil, errors.New("unknown marker type")
}
trials := 1
for breakConnection && !resetConnection {
if trials > 3 {
return nil, errors.New("connection break")
}
packetData, err = readPacketData()
if err != nil {
return nil, err
}
pck = newMarkerPacketFromData(packetData, session.Context)
if pck == nil {
return nil, errors.New("connection break")
}
switch pck.markerType {
case 0:
breakConnection = true
case 1:
if pck.markerData == 2 {
resetConnection = true
} else {
breakConnection = true
}
default:
return nil, errors.New("unknown marker type")
}
trials++
}
session.ResetBuffer()
err = session.writePacket(newMarkerPacket(2, session.Context))
if err != nil {
return nil, err
}
if resetConnection && session.Context.AdvancedService.HashAlgo != nil {
err = session.Context.AdvancedService.HashAlgo.Init()
if err != nil {
return nil, err
}
}
packetData, err = readPacketData()
if err != nil {
return nil, err
}
dataPck, err := newDataPacketFromData(packetData, session.Context)
if err != nil {
return nil, err
}
if dataPck == nil {
return nil, errors.New("connection break")
}
session.inBuffer = dataPck.buffer
session.index = 0
loop := true
for loop {
msg, err := session.GetByte()
if err != nil {
return nil, err
}
switch msg {
case 4:
loop = false
session.Summary, err = NewSummary(session)
if err != nil {
return nil, err
}
if session.HasError() {
return nil, session.GetError()
}
case 8:
size, err := session.GetInt(2, true, true)
if err != nil {
return nil, err
}
for x := 0; x < 2; x++ {
_, err = session.GetInt(4, true, true)
if err != nil {
return nil, err
}
}
for x := 2; x < size; x++ {
_, err = session.GetInt(4, true, true)
if err != nil {
return nil, err
}
}
_, err = session.GetInt(2, true, true)
if err != nil {
return nil, err
}
size, err = session.GetInt(2, true, true)
for x := 0; x < size; x++ {
_, val, num, err := session.GetKeyVal()
if err != nil {
return nil, err
}
if num == 163 {
session.TimeZone = val
}
}
if session.TTCVersion >= 4 {
// get queryID
size, err = session.GetInt(4, true, true)
if err != nil {
return nil, err
}
if size > 0 {
bty, err := session.GetBytes(size)
if err != nil {
return nil, err
}
if len(bty) >= 8 {
queryID := binary.LittleEndian.Uint64(bty[size-8:])
fmt.Println("query ID: ", queryID)
}
}
}
if session.TTCVersion >= 7 {
length, err := session.GetInt(4, true, true)
if err != nil {
return nil, err
}
for i := 0; i < length; i++ {
_, err = session.GetInt(8, true, true)
if err != nil {
return nil, err
}
}
}
default:
return nil, errors.New(fmt.Sprintf("TTC error: received code %d during stmt reading", msg))
}
}
fallthrough
default:
return nil, nil
}
}
// PutString write a string data to output buffer
func (session *Session) PutString(data string) {
session.PutClr([]byte(data))
}
// GetString read a string data from input buffer
func (session *Session) GetString(length int) (string, error) {
ret, err := session.GetClr()
return string(ret[:length]), err
}
// PutBytes write bytes of data to output buffer
func (session *Session) PutBytes(data ...byte) {
session.outBuffer.Write(data)
}
// PutUint write uint number with size entered either use bigEndian or not and use compression or not to
func (session *Session) PutUint(number interface{}, size uint8, bigEndian, compress bool) {
var num uint64
switch number := number.(type) {
case int64:
num = uint64(number)
case int32:
num = uint64(number)
case int16:
num = uint64(number)
case int8:
num = uint64(number)
case uint64:
num = number
case uint32:
num = uint64(number)
case uint16:
num = uint64(number)
case uint8:
num = uint64(number)
case uint:
num = uint64(number)
case int:
num = uint64(number)
default:
panic("you need to pass an integer to this function")
}
if size == 1 {
session.outBuffer.WriteByte(uint8(num))
//session.OutBuffer = append(session.OutBuffer, uint8(num))
return
}
if compress {
// if the size is one byte no compression occur only one byte written
temp := make([]byte, 8)
binary.BigEndian.PutUint64(temp, num)
temp = bytes.TrimLeft(temp, "\x00")
if size > uint8(len(temp)) {
size = uint8(len(temp))
}
if size == 0 {
session.outBuffer.WriteByte(0)
//session.OutBuffer = append(session.OutBuffer, 0)
} else {
session.outBuffer.WriteByte(size)
session.outBuffer.Write(temp)
//session.OutBuffer = append(session.OutBuffer, size)
//session.OutBuffer = append(session.OutBuffer, temp...)
}
} else {
temp := make([]byte, size)
if bigEndian {
switch size {
case 2:
binary.BigEndian.PutUint16(temp, uint16(num))
case 4:
binary.BigEndian.PutUint32(temp, uint32(num))
case 8:
binary.BigEndian.PutUint64(temp, num)
}
} else {
switch size {
case 2:
binary.LittleEndian.PutUint16(temp, uint16(num))
case 4:
binary.LittleEndian.PutUint32(temp, uint32(num))
case 8:
binary.LittleEndian.PutUint64(temp, num)
}
}
session.outBuffer.Write(temp)
//session.OutBuffer = append(session.OutBuffer, temp...)
}
}
// PutInt write int number with size entered either use bigEndian or not and use compression or not to
func (session *Session) PutInt(number interface{}, size uint8, bigEndian bool, compress bool) {
var num int64
switch number := number.(type) {
case int64:
num = number
case int32:
num = int64(number)
case int16:
num = int64(number)
case int8:
num = int64(number)
case uint64:
num = int64(number)
case uint32:
num = int64(number)
case uint16:
num = int64(number)
case uint8:
num = int64(number)
case uint:
num = int64(number)
case int:
num = int64(number)
default:
panic("you need to pass an integer to this function")
}
if compress {
temp := make([]byte, 8)
binary.BigEndian.PutUint64(temp, uint64(num))
temp = bytes.TrimLeft(temp, "\x00")
if size > uint8(len(temp)) {
size = uint8(len(temp))
}
if size == 0 {
session.outBuffer.WriteByte(0)
//session.OutBuffer = append(session.OutBuffer, 0)
} else {
if num < 0 {
num = num * -1
size = size & 0x80
}
session.outBuffer.WriteByte(size)
session.outBuffer.Write(temp)
}
} else {
if size == 1 {
session.outBuffer.WriteByte(uint8(num))
} else {
temp := make([]byte, size)
if bigEndian {
switch size {
case 2:
binary.BigEndian.PutUint16(temp, uint16(num))
case 4:
binary.BigEndian.PutUint32(temp, uint32(num))
case 8:
binary.BigEndian.PutUint64(temp, uint64(num))
}
} else {
switch size {
case 2:
binary.LittleEndian.PutUint16(temp, uint16(num))
case 4:
binary.LittleEndian.PutUint32(temp, uint32(num))
case 8:
binary.LittleEndian.PutUint64(temp, uint64(num))
}
}
session.outBuffer.Write(temp)
}
}
}
// PutClr write variable length bytearray to output buffer
func (session *Session) PutClr(data []byte) {
dataLen := len(data)
if dataLen > 0xFC {
session.outBuffer.WriteByte(0xFE)
start := 0
for start < dataLen {
end := start + session.ClrChunkSize
if end > dataLen {
end = dataLen
}
temp := data[start:end]
if session.UseBigClrChunks {
session.PutInt(len(temp), 4, true, true)
} else {
session.outBuffer.WriteByte(uint8(len(temp)))
}
session.outBuffer.Write(temp)
start += session.ClrChunkSize
}
session.outBuffer.WriteByte(0)
} else if dataLen == 0 {
session.outBuffer.WriteByte(0)
} else {
session.outBuffer.WriteByte(uint8(len(data)))
session.outBuffer.Write(data)
}
}
// PutKeyValString write key, val (in form of string) and flag number to output buffer
func (session *Session) PutKeyValString(key string, val string, num uint8) {
session.PutKeyVal([]byte(key), []byte(val), num)
}
// PutKeyVal write key, val (in form of bytearray) and flag number to output buffer
func (session *Session) PutKeyVal(key []byte, val []byte, num uint8) {
if len(key) == 0 {
session.outBuffer.WriteByte(0)
} else {
session.PutUint(len(key), 4, true, true)
session.PutClr(key)
}
if len(val) == 0 {
session.outBuffer.WriteByte(0)
} else {
session.PutUint(len(val), 4, true, true)
session.PutClr(val)
}
session.PutInt(num, 4, true, true)
}