-
Notifications
You must be signed in to change notification settings - Fork 7
/
connection.go
1059 lines (854 loc) · 29.8 KB
/
connection.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 connection
import (
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
"net"
"sync"
"time"
"github.com/cyverse/go-irodsclient/irods/auth"
"github.com/cyverse/go-irodsclient/irods/common"
"github.com/cyverse/go-irodsclient/irods/message"
"github.com/cyverse/go-irodsclient/irods/metrics"
"github.com/cyverse/go-irodsclient/irods/types"
"github.com/cyverse/go-irodsclient/irods/util"
"golang.org/x/xerrors"
log "github.com/sirupsen/logrus"
)
const (
TCPBufferSizeDefault int = 4 * 1024 * 1024
)
// IRODSConnection connects to iRODS
type IRODSConnection struct {
account *types.IRODSAccount
requestTimeout time.Duration
tcpBufferSize int
applicationName string
connected bool
isSSLSocket bool
socket net.Conn
serverVersion *types.IRODSVersion
sslSharedSecret []byte
creationTime time.Time
lastSuccessfulAccess time.Time
clientSignature string
dirtyTransaction bool
mutex sync.Mutex
locked bool // true if mutex is locked
metrics *metrics.IRODSMetrics
}
// NewIRODSConnection create a IRODSConnection
func NewIRODSConnection(account *types.IRODSAccount, requestTimeout time.Duration, applicationName string) *IRODSConnection {
return &IRODSConnection{
account: account,
requestTimeout: requestTimeout,
tcpBufferSize: TCPBufferSizeDefault,
applicationName: applicationName,
creationTime: time.Now(),
clientSignature: "",
dirtyTransaction: false,
mutex: sync.Mutex{},
metrics: &metrics.IRODSMetrics{},
}
}
// NewIRODSConnectionWithMetrics create a IRODSConnection
func NewIRODSConnectionWithMetrics(account *types.IRODSAccount, requestTimeout time.Duration, applicationName string, metrics *metrics.IRODSMetrics) *IRODSConnection {
return &IRODSConnection{
account: account,
requestTimeout: requestTimeout,
tcpBufferSize: TCPBufferSizeDefault,
applicationName: applicationName,
creationTime: time.Now(),
clientSignature: "",
dirtyTransaction: false,
mutex: sync.Mutex{},
metrics: metrics,
}
}
// Lock locks connection
func (conn *IRODSConnection) Lock() {
conn.mutex.Lock()
conn.locked = true
}
// Unlock unlocks connection
func (conn *IRODSConnection) Unlock() {
conn.locked = false
conn.mutex.Unlock()
}
// GetAccount returns iRODSAccount
func (conn *IRODSConnection) GetAccount() *types.IRODSAccount {
return conn.account
}
// GetVersion returns iRODS version
func (conn *IRODSConnection) GetVersion() *types.IRODSVersion {
return conn.serverVersion
}
// SetTCPBufferSize sets TCP Buffer Size
func (conn *IRODSConnection) SetTCPBufferSize(bufferSize int) {
conn.tcpBufferSize = bufferSize
}
// SupportParallelUpload checks if the server supports parallel upload
// available from 4.2.9
func (conn *IRODSConnection) SupportParallelUpload() bool {
return conn.serverVersion.HasHigherVersionThan(4, 2, 9)
}
func (conn *IRODSConnection) requiresCSNegotiation() bool {
return conn.account.ClientServerNegotiation
}
// GetPAMToken returns server generated token For PAM Auth
func (conn *IRODSConnection) GetPAMToken() string {
return conn.account.PamToken
}
// GetSSLSharedSecret returns ssl shared secret
func (conn *IRODSConnection) GetSSLSharedSecret() []byte {
return conn.sslSharedSecret
}
// IsConnected returns if the connection is live
func (conn *IRODSConnection) IsConnected() bool {
return conn.connected
}
// IsSSL returns if the connection is ssl
func (conn *IRODSConnection) IsSSL() bool {
return conn.isSSLSocket
}
// GetCreationTime returns creation time
func (conn *IRODSConnection) GetCreationTime() time.Time {
return conn.creationTime
}
// GetLastSuccessfulAccess returns last successful access time
func (conn *IRODSConnection) GetLastSuccessfulAccess() time.Time {
return conn.lastSuccessfulAccess
}
// GetClientSignature returns client signature to be used in password obfuscation
func (conn *IRODSConnection) GetClientSignature() string {
return conn.clientSignature
}
// SetTransactionDirty sets if transaction is dirty
func (conn *IRODSConnection) SetTransactionDirty(dirtyTransaction bool) {
conn.dirtyTransaction = dirtyTransaction
}
// IsTransactionDirty returns true if transaction is dirty
func (conn *IRODSConnection) IsTransactionDirty() bool {
return conn.dirtyTransaction
}
// setSocketOpt sets socket opts
func (conn *IRODSConnection) setSocketOpt(socket net.Conn, bufferSize int) {
logger := log.WithFields(log.Fields{
"package": "connection",
"struct": "IRODSConnection",
"function": "setSocketOpt",
})
if tcpSocket, ok := socket.(*net.TCPConn); ok {
// TCP socket
// nodelay is default
//tcpSocket.SetNoDelay(true)
tcpSocket.SetKeepAlive(true)
// TCP buffer size
if bufferSize <= 0 {
bufferSize = TCPBufferSizeDefault
}
sockErr := tcpSocket.SetReadBuffer(bufferSize)
if sockErr != nil {
sockBuffErr := xerrors.Errorf("failed to set tcp read buffer size %d: %w", bufferSize, sockErr)
logger.Errorf("%+v", sockBuffErr)
}
sockErr = tcpSocket.SetWriteBuffer(bufferSize)
if sockErr != nil {
sockBuffErr := xerrors.Errorf("failed to set tcp write buffer size %d: %w", bufferSize, sockErr)
logger.Errorf("%+v", sockBuffErr)
}
}
}
// Connect connects to iRODS
func (conn *IRODSConnection) Connect() error {
logger := log.WithFields(log.Fields{
"package": "connection",
"struct": "IRODSConnection",
"function": "Connect",
})
conn.connected = false
conn.account.FixAuthConfiguration()
err := conn.account.Validate()
if err != nil {
return xerrors.Errorf("invalid account (%s): %w", err.Error(), types.NewConnectionConfigError(conn.account))
}
// lock the connection
conn.Lock()
defer conn.Unlock()
server := fmt.Sprintf("%s:%d", conn.account.Host, conn.account.Port)
logger.Debugf("Connecting to %s", server)
// must connect to the server in 10 sec
var dialer net.Dialer
ctx, cancelFunc := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelFunc()
socket, err := dialer.DialContext(ctx, "tcp", server)
if err != nil {
connErr := xerrors.Errorf("failed to connect to specified host %s and port %d (%s): %w", conn.account.Host, conn.account.Port, err.Error(), types.NewConnectionError())
logger.Errorf("%+v", connErr)
if conn.metrics != nil {
conn.metrics.IncreaseCounterForConnectionFailures(1)
}
return connErr
}
conn.setSocketOpt(socket, conn.tcpBufferSize)
if conn.metrics != nil {
conn.metrics.IncreaseConnectionsOpened(1)
}
conn.socket = socket
var irodsVersion *types.IRODSVersion
if conn.requiresCSNegotiation() {
// client-server negotiation
irodsVersion, err = conn.connectWithCSNegotiation()
} else {
// No client-server negotiation
irodsVersion, err = conn.connectWithoutCSNegotiation()
}
if err != nil {
connErr := xerrors.Errorf("failed to startup an iRODS connection to server %s and port %d (%s): %w", conn.account.Host, conn.account.Port, err.Error(), types.NewConnectionError())
logger.Errorf("%+v", connErr)
_ = conn.disconnectNow()
if conn.metrics != nil {
conn.metrics.IncreaseCounterForConnectionFailures(1)
}
return connErr
}
conn.serverVersion = irodsVersion
switch conn.account.AuthenticationScheme {
case types.AuthSchemeNative:
err = conn.loginNative()
case types.AuthSchemeGSI:
err = conn.loginGSI()
case types.AuthSchemePAM:
if len(conn.account.PamToken) > 0 {
err = conn.loginPAMWithToken()
} else {
err = conn.loginPAMWithPassword()
}
default:
err = xerrors.Errorf("unknown Authentication Scheme - %s: %w", conn.account.AuthenticationScheme, types.NewConnectionConfigError(conn.account))
}
if err != nil {
connErr := xerrors.Errorf("failed to login to irods: %w", err)
logger.Errorf("%+v", connErr)
_ = conn.disconnectNow()
return connErr
}
if conn.account.UseTicket() {
req := message.NewIRODSMessageTicketAdminRequest("session", conn.account.Ticket)
err := conn.RequestAndCheck(req, &message.IRODSMessageAdminResponse{}, nil)
if err != nil {
return xerrors.Errorf("received supply ticket error (%s): %w", err.Error(), types.NewAuthError(conn.account))
}
}
conn.connected = true
conn.lastSuccessfulAccess = time.Now()
return nil
}
func (conn *IRODSConnection) connectWithCSNegotiation() (*types.IRODSVersion, error) {
logger := log.WithFields(log.Fields{
"package": "connection",
"struct": "IRODSConnection",
"function": "connectWithCSNegotiation",
})
// Get client negotiation policy
clientPolicy := types.CSNegotiationRequireTCP
if len(conn.account.CSNegotiationPolicy) > 0 {
clientPolicy = conn.account.CSNegotiationPolicy
}
// Send a startup message
logger.Debug("Start up a connection with CS Negotiation")
startup := message.NewIRODSMessageStartupPack(conn.account, conn.applicationName, true)
err := conn.RequestWithoutResponse(startup)
if err != nil {
return nil, xerrors.Errorf("failed to send startup (%s): %w", err.Error(), types.NewConnectionError())
}
// Server responds with negotiation response
negotiationMessage, err := conn.ReadMessage(nil)
if err != nil {
return nil, xerrors.Errorf("failed to receive negotiation message (%s): %w", err.Error(), types.NewConnectionError())
}
if negotiationMessage.Body == nil {
return nil, xerrors.Errorf("failed to receive negotiation message body: %w", types.NewConnectionError())
}
if negotiationMessage.Body.Type == message.RODS_MESSAGE_VERSION_TYPE {
// this happens when an error occur
// Server responds with version
version := message.IRODSMessageVersion{}
err = version.FromMessage(negotiationMessage)
if err != nil {
return nil, xerrors.Errorf("failed to receive negotiation message (%s): %w", err.Error(), types.NewConnectionError())
}
return version.GetVersion(), nil
} else if negotiationMessage.Body.Type == message.RODS_MESSAGE_CS_NEG_TYPE {
// Server responds with its own negotiation policy
logger.Debug("Start up CS Negotiation")
negotiation := message.IRODSMessageCSNegotiation{}
err = negotiation.FromMessage(negotiationMessage)
if err != nil {
return nil, xerrors.Errorf("failed to receive negotiation message (%s): %w", err.Error(), types.NewConnectionError())
}
serverPolicy, err := types.GetCSNegotiationRequire(negotiation.Result)
if err != nil {
return nil, xerrors.Errorf("failed to parse server policy (%s): %w", err.Error(), types.NewConnectionError())
}
logger.Debugf("Client policy - %s, server policy - %s", clientPolicy, serverPolicy)
// Perform the negotiation
policyResult := types.PerformCSNegotiation(clientPolicy, serverPolicy)
// If negotiation failed we're done
if policyResult == types.CSNegotiationFailure {
return nil, xerrors.Errorf("client-server negotiation failed - %s, %s: %w", string(clientPolicy), string(serverPolicy), types.NewConnectionError())
}
// Send negotiation result to server
negotiationResult := message.NewIRODSMessageCSNegotiation(policyResult)
version := message.IRODSMessageVersion{}
err = conn.Request(negotiationResult, &version, nil)
if err != nil {
return nil, xerrors.Errorf("failed to receive version message (%s): %w", err.Error(), types.NewConnectionError())
}
if policyResult == types.CSNegotiationUseSSL {
err := conn.sslStartup()
if err != nil {
return nil, xerrors.Errorf("failed to start up SSL: %w", err)
}
}
return version.GetVersion(), nil
}
return nil, xerrors.Errorf("unknown response message '%s': %w", negotiationMessage.Body.Type, types.NewConnectionError())
}
func (conn *IRODSConnection) connectWithoutCSNegotiation() (*types.IRODSVersion, error) {
logger := log.WithFields(log.Fields{
"package": "connection",
"struct": "IRODSConnection",
"function": "connectWithoutCSNegotiation",
})
// No client-server negotiation
// Send a startup message
logger.Debug("Start up connection without CS Negotiation")
startup := message.NewIRODSMessageStartupPack(conn.account, conn.applicationName, false)
version := message.IRODSMessageVersion{}
err := conn.Request(startup, &version, nil)
if err != nil {
return nil, xerrors.Errorf("failed to receive version message (%s): %w", err.Error(), types.NewConnectionError())
}
return version.GetVersion(), nil
}
func (conn *IRODSConnection) sslStartup() error {
logger := log.WithFields(log.Fields{
"package": "connection",
"struct": "IRODSConnection",
"function": "sslStartup",
})
logger.Debug("Start up SSL")
irodsSSLConfig := conn.account.SSLConfiguration
if irodsSSLConfig == nil {
return xerrors.Errorf("SSL Configuration is not set: %w", types.NewConnectionConfigError(conn.account))
}
caCertPool, err := irodsSSLConfig.LoadCACert()
if err != nil {
return xerrors.Errorf("Failed to load CA Certificates: %w", err)
}
serverName := conn.account.Host
if conn.account.ServerNameTLS != "" {
serverName = conn.account.ServerNameTLS
}
sslConf := &tls.Config{
RootCAs: caCertPool,
ServerName: serverName,
InsecureSkipVerify: conn.account.SkipVerifyTLS,
}
// Create a side connection using the existing socket
sslSocket := tls.Client(conn.socket, sslConf)
err = sslSocket.Handshake()
if err != nil {
return xerrors.Errorf("SSL Handshake error (%s): %w", err.Error(), types.NewConnectionError())
}
// from now on use ssl socket
conn.socket = sslSocket
conn.isSSLSocket = true
// Generate a key (shared secret)
encryptionKey := make([]byte, irodsSSLConfig.EncryptionKeySize)
_, err = rand.Read(encryptionKey)
if err != nil {
return xerrors.Errorf("failed to generate shared secret (%s): %w", err.Error(), types.NewConnectionError())
}
// Send a ssl setting
sslSetting := message.NewIRODSMessageSSLSettings(irodsSSLConfig.EncryptionAlgorithm, irodsSSLConfig.EncryptionKeySize, irodsSSLConfig.SaltSize, irodsSSLConfig.HashRounds)
err = conn.RequestWithoutResponse(sslSetting)
if err != nil {
return xerrors.Errorf("failed to send ssl setting message (%s): %w", err.Error(), types.NewConnectionError())
}
// Send a shared secret
sslSharedSecret := message.NewIRODSMessageSSLSharedSecret(encryptionKey)
err = conn.RequestWithoutResponseNoXML(sslSharedSecret)
if err != nil {
return xerrors.Errorf("failed to send ssl shared secret message (%s): %w", err.Error(), types.NewConnectionError())
}
conn.sslSharedSecret = encryptionKey
return nil
}
func (conn *IRODSConnection) login(password string) error {
// authenticate
authRequest := message.NewIRODSMessageAuthRequest()
authChallenge := message.IRODSMessageAuthChallengeResponse{}
err := conn.Request(authRequest, &authChallenge, nil)
if err != nil {
return xerrors.Errorf("failed to receive authentication challenge message body (%s): %w", err.Error(), types.NewAuthError(conn.account))
}
challengeBytes, err := authChallenge.GetChallenge()
if err != nil {
return xerrors.Errorf("failed to get authentication challenge (%s): %w", err.Error(), types.NewAuthError(conn.account))
}
// save client signature
conn.clientSignature = conn.createClientSignature(challengeBytes)
encodedPassword := auth.GenerateAuthResponse(challengeBytes, password)
authResponse := message.NewIRODSMessageAuthResponse(encodedPassword, conn.account.ProxyUser)
authResult := message.IRODSMessageAuthResult{}
err = conn.RequestAndCheck(authResponse, &authResult, nil)
if err != nil {
return xerrors.Errorf("received irods authentication error (%s): %w", err.Error(), types.NewAuthError(conn.account))
}
return nil
}
func (conn *IRODSConnection) loginNative() error {
logger := log.WithFields(log.Fields{
"package": "connection",
"struct": "IRODSConnection",
"function": "loginNative",
})
logger.Debug("Logging in using native authentication method")
return conn.login(conn.account.Password)
}
func (conn *IRODSConnection) loginGSI() error {
return xerrors.Errorf("GSI login is not yet implemented: %w", types.NewAuthError(conn.account))
}
func (conn *IRODSConnection) loginPAMWithPassword() error {
logger := log.WithFields(log.Fields{
"package": "connection",
"struct": "IRODSConnection",
"function": "loginPAMWithPassword",
})
logger.Debug("Logging in using pam authentication method")
// Check whether ssl has already started, if not, start ssl.
if _, ok := conn.socket.(*tls.Conn); !ok {
return xerrors.Errorf("connection should be using SSL: %w", types.NewConnectionError())
}
ttl := conn.account.PamTTL
if ttl <= 0 {
ttl = 1
}
// authenticate
pamAuthRequest := message.NewIRODSMessagePamAuthRequest(conn.account.ClientUser, conn.account.Password, ttl)
pamAuthResponse := message.IRODSMessagePamAuthResponse{}
err := conn.Request(pamAuthRequest, &pamAuthResponse, nil)
if err != nil {
return xerrors.Errorf("failed to receive an authentication challenge message (%s): %w", err.Error(), types.NewAuthError(conn.account))
}
// save irods generated password for possible future use
conn.account.PamToken = pamAuthResponse.GeneratedPassword
// retry native auth with generated password
return conn.login(conn.account.PamToken)
}
func (conn *IRODSConnection) loginPAMWithToken() error {
logger := log.WithFields(log.Fields{
"package": "connection",
"struct": "IRODSConnection",
"function": "loginPAMWithToken",
})
logger.Debug("Logging in using pam authentication method")
// Check whether ssl has already started, if not, start ssl.
if _, ok := conn.socket.(*tls.Conn); !ok {
return xerrors.Errorf("connection should be using SSL: %w", types.NewConnectionError())
}
ttl := conn.account.PamTTL
if ttl <= 0 {
ttl = 1
}
// retry native auth with generated password
return conn.login(conn.account.PamToken)
}
// Disconnect disconnects
func (conn *IRODSConnection) disconnectNow() error {
conn.connected = false
var err error
if conn.socket != nil {
err = conn.socket.Close()
conn.socket = nil
}
if conn.metrics != nil {
conn.metrics.DecreaseConnectionsOpened(1)
}
if err == nil {
return nil
}
return xerrors.Errorf("failed to close socket: %w", err)
}
// Disconnect disconnects
func (conn *IRODSConnection) Disconnect() error {
logger := log.WithFields(log.Fields{
"package": "connection",
"struct": "IRODSConnection",
"function": "Disconnect",
})
logger.Debug("Disconnecting the connection")
// lock the connection
conn.Lock()
defer conn.Unlock()
disconnect := message.NewIRODSMessageDisconnect()
err := conn.RequestWithoutResponse(disconnect)
conn.lastSuccessfulAccess = time.Now()
err2 := conn.disconnectNow()
if err2 != nil {
return err2
}
if err != nil {
return err
}
return nil
}
func (conn *IRODSConnection) socketFail() {
if conn.metrics != nil {
conn.metrics.IncreaseCounterForConnectionFailures(1)
}
conn.disconnectNow()
}
// Send sends data
func (conn *IRODSConnection) Send(buffer []byte, size int) error {
return conn.SendWithTrackerCallBack(buffer, size, nil)
}
// SendWithTrackerCallBack sends data
func (conn *IRODSConnection) SendWithTrackerCallBack(buffer []byte, size int, callback common.TrackerCallBack) error {
if conn.socket == nil {
return xerrors.Errorf("failed to send data - socket closed")
}
if !conn.locked {
return xerrors.Errorf("connection must be locked before use")
}
if conn.requestTimeout > 0 {
conn.socket.SetWriteDeadline(time.Now().Add(conn.requestTimeout))
}
err := util.WriteBytesWithTrackerCallBack(conn.socket, buffer, size, callback)
if err != nil {
conn.socketFail()
return xerrors.Errorf("failed to send data: %w", err)
}
if size > 0 {
if conn.metrics != nil {
conn.metrics.IncreaseBytesSent(uint64(size))
}
}
conn.lastSuccessfulAccess = time.Now()
return nil
}
// SendFromReader sends data from Reader
func (conn *IRODSConnection) SendFromReader(src io.Reader, size int64) error {
if conn.socket == nil {
return xerrors.Errorf("failed to send data - socket closed")
}
if !conn.locked {
return xerrors.Errorf("connection must be locked before use")
}
if conn.requestTimeout > 0 {
conn.socket.SetWriteDeadline(time.Now().Add(conn.requestTimeout))
}
copyLen, err := io.CopyN(conn.socket, src, size)
if copyLen != size {
return xerrors.Errorf("failed to send data. src returned EOF (requested %d, copied %d)", size, copyLen)
}
if copyLen > 0 {
if conn.metrics != nil {
conn.metrics.IncreaseBytesSent(uint64(copyLen))
}
}
if err != nil {
if err != io.EOF {
conn.socketFail()
return xerrors.Errorf("failed to send data: %w", err)
}
}
conn.lastSuccessfulAccess = time.Now()
return nil
}
// Recv receives a message
func (conn *IRODSConnection) Recv(buffer []byte, size int) (int, error) {
return conn.RecvWithTrackerCallBack(buffer, size, nil)
}
// Recv receives a message
func (conn *IRODSConnection) RecvWithTrackerCallBack(buffer []byte, size int, callback common.TrackerCallBack) (int, error) {
if conn.socket == nil {
return 0, xerrors.Errorf("failed to receive data - socket closed")
}
if !conn.locked {
return 0, xerrors.Errorf("connection must be locked before use")
}
if conn.requestTimeout > 0 {
conn.socket.SetReadDeadline(time.Now().Add(conn.requestTimeout))
}
readLen, err := util.ReadBytesWithTrackerCallBack(conn.socket, buffer, size, callback)
if err != nil {
conn.socketFail()
return readLen, xerrors.Errorf("failed to receive data: %w", err)
}
if readLen > 0 {
if conn.metrics != nil {
conn.metrics.IncreaseBytesReceived(uint64(readLen))
}
}
conn.lastSuccessfulAccess = time.Now()
return readLen, nil
}
// RecvToWriter receives a message to Writer
func (conn *IRODSConnection) RecvToWriter(writer io.Writer, size int64) (int64, error) {
if conn.socket == nil {
return 0, xerrors.Errorf("failed to receive data - socket closed")
}
if !conn.locked {
return 0, xerrors.Errorf("connection must be locked before use")
}
if conn.requestTimeout > 0 {
conn.socket.SetReadDeadline(time.Now().Add(conn.requestTimeout))
}
copyLen, err := io.CopyN(writer, conn.socket, size)
if copyLen > 0 {
if conn.metrics != nil {
conn.metrics.IncreaseBytesReceived(uint64(copyLen))
}
}
if err != nil {
if err != io.EOF {
conn.socketFail()
return copyLen, xerrors.Errorf("failed to receive data: %w", err)
}
}
conn.lastSuccessfulAccess = time.Now()
return copyLen, nil
}
// SendMessage makes the message into bytes
func (conn *IRODSConnection) SendMessage(msg *message.IRODSMessage) error {
return conn.SendMessageWithTrackerCallBack(msg, nil)
}
// SendMessageWithTrackerCallBack makes the message into bytes
func (conn *IRODSConnection) SendMessageWithTrackerCallBack(msg *message.IRODSMessage, callback common.TrackerCallBack) error {
if !conn.locked {
return xerrors.Errorf("connection must be locked before use")
}
messageBuffer := new(bytes.Buffer)
if msg.Header == nil && msg.Body == nil {
return xerrors.Errorf("header and body cannot be nil")
}
var headerBytes []byte
var err error
messageLen := 0
errorLen := 0
bsLen := 0
if msg.Body != nil {
if msg.Body.Message != nil {
messageLen = len(msg.Body.Message)
}
if msg.Body.Error != nil {
errorLen = len(msg.Body.Error)
}
if msg.Body.Bs != nil {
bsLen = len(msg.Body.Bs)
}
if msg.Header == nil {
h := message.MakeIRODSMessageHeader(msg.Body.Type, uint32(messageLen), uint32(errorLen), uint32(bsLen), msg.Body.IntInfo)
headerBytes, err = h.GetBytes()
if err != nil {
return err
}
}
}
if msg.Header != nil {
headerBytes, err = msg.Header.GetBytes()
if err != nil {
return err
}
}
// pack length - Big Endian
headerLenBuffer := make([]byte, 4)
binary.BigEndian.PutUint32(headerLenBuffer, uint32(len(headerBytes)))
// header
messageBuffer.Write(headerLenBuffer)
messageBuffer.Write(headerBytes)
if msg.Body != nil {
bodyBytes, err := msg.Body.GetBytesWithoutBS()
if err != nil {
return err
}
// body
messageBuffer.Write(bodyBytes)
}
// send
bytes := messageBuffer.Bytes()
err = conn.Send(bytes, len(bytes))
if err != nil {
return xerrors.Errorf("failed to send message: %w", err)
}
// send body-bs
if msg.Body != nil {
if msg.Body.Bs != nil {
conn.SendWithTrackerCallBack(msg.Body.Bs, len(msg.Body.Bs), callback)
}
}
return nil
}
// readMessageHeader reads data from the given connection and returns iRODSMessageHeader
func (conn *IRODSConnection) readMessageHeader() (*message.IRODSMessageHeader, error) {
// read header size
headerLenBuffer := make([]byte, 4)
readLen, err := conn.Recv(headerLenBuffer, 4)
if err != nil {
return nil, xerrors.Errorf("failed to read header size: %w", err)
}
if readLen != 4 {
return nil, xerrors.Errorf("failed to read header size, read %d", readLen)
}
headerSize := binary.BigEndian.Uint32(headerLenBuffer)
if headerSize <= 0 {
return nil, xerrors.Errorf("invalid header size returned - len = %d", headerSize)
}
// read header
headerBuffer := make([]byte, headerSize)
readLen, err = conn.Recv(headerBuffer, int(headerSize))
if err != nil {
return nil, xerrors.Errorf("failed to read header: %w", err)
}
if readLen != int(headerSize) {
return nil, xerrors.Errorf("failed to read header fully - %d requested but %d read", headerSize, readLen)
}
header := message.IRODSMessageHeader{}
err = header.FromBytes(headerBuffer)
if err != nil {
return nil, err
}
return &header, nil
}
// ReadMessage reads data from the given socket and returns IRODSMessage
// if bsBuffer is given, bs data will be written directly to the bsBuffer
// if not given, a new buffer will be allocated.
func (conn *IRODSConnection) ReadMessage(bsBuffer []byte) (*message.IRODSMessage, error) {
return conn.ReadMessageWithTrackerCallBack(bsBuffer, nil)
}
func (conn *IRODSConnection) ReadMessageWithTrackerCallBack(bsBuffer []byte, callback common.TrackerCallBack) (*message.IRODSMessage, error) {
if !conn.locked {
return nil, xerrors.Errorf("connection must be locked before use")
}
header, err := conn.readMessageHeader()
if err != nil {
return nil, err
}
// read body
bodyLen := header.MessageLen + header.ErrorLen
bodyBuffer := make([]byte, bodyLen)
if bsBuffer == nil {
bsBuffer = make([]byte, int(header.BsLen))
} else if len(bsBuffer) < int(header.BsLen) {
return nil, xerrors.Errorf("provided bs buffer is too short, %d size is given, but %d size is required", len(bsBuffer), int(header.BsLen))
}
bodyReadLen, err := conn.Recv(bodyBuffer, int(bodyLen))
if err != nil {
return nil, xerrors.Errorf("failed to read body: %w", err)
}
if bodyReadLen != int(bodyLen) {
return nil, xerrors.Errorf("failed to read body fully - %d requested but %d read", bodyLen, bodyReadLen)
}
bsReadLen, err := conn.RecvWithTrackerCallBack(bsBuffer, int(header.BsLen), callback)
if err != nil {
return nil, xerrors.Errorf("failed to read body (BS): %w", err)
}
if bsReadLen != int(header.BsLen) {
return nil, xerrors.Errorf("failed to read body (BS) fully - %d requested but %d read", int(header.BsLen), bsReadLen)
}
body := message.IRODSMessageBody{}
err = body.FromBytes(header, bodyBuffer, bsBuffer[:int(header.BsLen)])
if err != nil {
return nil, err
}
body.Type = header.Type
body.IntInfo = header.IntInfo
return &message.IRODSMessage{
Header: header,
Body: &body,
}, nil
}
// Commit a transaction. This is useful in combination with the NO_COMMIT_FLAG.
// Usage is limited to privileged accounts.
func (conn *IRODSConnection) Commit() error {
if !conn.locked {
return xerrors.Errorf("connection must be locked before use")
}
return conn.endTransaction(true)
}
// Rollback a transaction. This is useful in combination with the NO_COMMIT_FLAG.
// It can also be used to clear the current database transaction if there are no staged operations,
// just to refresh the view on the database for future queries.
// Usage is limited to privileged accounts.
func (conn *IRODSConnection) Rollback() error {
if !conn.locked {
return xerrors.Errorf("connection must be locked before use")
}
return conn.endTransaction(false)
}
// PoorMansRollback rolls back a transaction as a nonprivileged account, bypassing API limitations.
// A nonprivileged account cannot have staged operations, so rollback is always a no-op.
// The usage for this function, is that rolling back the current database transaction still will start
// a new one, so that future queries will see all changes that where made up to calling this function.
func (conn *IRODSConnection) PoorMansRollback() error {
if !conn.locked {
return xerrors.Errorf("connection must be locked before use")
}
dummyCol := fmt.Sprintf("/%s/home/%s", conn.account.ClientZone, conn.account.ClientUser)