-
Notifications
You must be signed in to change notification settings - Fork 149
/
XrdClXRootDMsgHandler.cc
1869 lines (1653 loc) · 70.8 KB
/
XrdClXRootDMsgHandler.cc
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
//------------------------------------------------------------------------------
// Copyright (c) 2011-2014 by European Organization for Nuclear Research (CERN)
// Author: Lukasz Janyst <ljanyst@cern.ch>
//------------------------------------------------------------------------------
// This file is part of the XRootD software suite.
//
// XRootD is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// XRootD is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with XRootD. If not, see <http://www.gnu.org/licenses/>.
//
// In applying this licence, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
//------------------------------------------------------------------------------
#include "XrdCl/XrdClXRootDMsgHandler.hh"
#include "XrdCl/XrdClLog.hh"
#include "XrdCl/XrdClDefaultEnv.hh"
#include "XrdCl/XrdClConstants.hh"
#include "XrdCl/XrdClXRootDTransport.hh"
#include "XrdCl/XrdClMessage.hh"
#include "XrdCl/XrdClURL.hh"
#include "XrdCl/XrdClUglyHacks.hh"
#include "XrdCl/XrdClUtils.hh"
#include "XrdCl/XrdClTaskManager.hh"
#include "XrdCl/XrdClSIDManager.hh"
#include "XrdCl/XrdClMessageUtils.hh"
#include <arpa/inet.h> // for network unmarshalling stuff
#include "XrdSys/XrdSysPlatform.hh" // same as above
#include <memory>
#include <sstream>
namespace
{
//----------------------------------------------------------------------------
// We need an extra task what will run the handler in the future, because
// tasks get deleted and we need the handler
//----------------------------------------------------------------------------
class WaitTask: public XrdCl::Task
{
public:
WaitTask( XrdCl::XRootDMsgHandler *handler ): pHandler( handler )
{
std::ostringstream o;
o << "WaitTask for: 0x" << handler->GetRequest();
SetName( o.str() );
}
virtual time_t Run( time_t now )
{
pHandler->WaitDone( now );
return 0;
}
private:
XrdCl::XRootDMsgHandler *pHandler;
};
};
namespace XrdCl
{
//----------------------------------------------------------------------------
// Examine an incoming message, and decide on the action to be taken
//----------------------------------------------------------------------------
uint16_t XRootDMsgHandler::Examine( Message *msg )
{
if( msg->GetSize() < 8 )
return Ignore;
ServerResponse *rsp = (ServerResponse *)msg->GetBuffer();
ClientRequest *req = (ClientRequest *)pRequest->GetBuffer();
uint16_t status = 0;
uint32_t dlen = 0;
//--------------------------------------------------------------------------
// We got an async message
//--------------------------------------------------------------------------
if( rsp->hdr.status == kXR_attn )
{
if( msg->GetSize() < 12 )
return Ignore;
//------------------------------------------------------------------------
// We only care about async responses
//------------------------------------------------------------------------
if( rsp->body.attn.actnum != (int32_t)htonl(kXR_asynresp) )
return Ignore;
if( msg->GetSize() < 24 )
return Ignore;
//------------------------------------------------------------------------
// Check if the message has the stream ID that we're interested in
//------------------------------------------------------------------------
ServerResponse *embRsp = (ServerResponse*)msg->GetBuffer(16);
if( embRsp->hdr.streamid[0] != req->header.streamid[0] ||
embRsp->hdr.streamid[1] != req->header.streamid[1] )
return Ignore;
status = ntohs( embRsp->hdr.status );
dlen = ntohl( embRsp->hdr.dlen );
}
//--------------------------------------------------------------------------
// We got a sync message - check if it belongs to us
//--------------------------------------------------------------------------
else
{
if( rsp->hdr.streamid[0] != req->header.streamid[0] ||
rsp->hdr.streamid[1] != req->header.streamid[1] )
return Ignore;
status = rsp->hdr.status;
dlen = rsp->hdr.dlen;
}
//--------------------------------------------------------------------------
// We take the ownership of the message and decide what we will do
// with the handler itself, the options are:
// 1) we want to either read in raw mode (the Raw flag) or have the message
// body reconstructed for us by the TransportHandler by the time
// Process() is called (default, no extra flag)
// 2) we either got a full response in which case we don't want to be
// notified about anything anymore (RemoveHandler) or we got a partial
// answer and we need to wait for more (default, no extra flag)
//--------------------------------------------------------------------------
pResponse = msg;
Log *log = DefaultEnv::GetLog();
switch( status )
{
//------------------------------------------------------------------------
// Handle the cached cases
//------------------------------------------------------------------------
case kXR_error:
case kXR_redirect:
case kXR_wait:
return Take | RemoveHandler;
case kXR_waitresp:
return Take;
//------------------------------------------------------------------------
// Handle the potential raw cases
//------------------------------------------------------------------------
case kXR_ok:
{
//----------------------------------------------------------------------
// For kXR_read we read in raw mode if we haven't got the full message
// already (handler installed to late and the message has been cached)
//----------------------------------------------------------------------
uint16_t reqId = ntohs( req->header.requestid );
if( reqId == kXR_read && msg->GetSize() == 8 )
{
pReadRawStarted = false;
pAsyncMsgSize = dlen;
return Take | Raw | RemoveHandler;
}
//----------------------------------------------------------------------
// kXR_readv is the same as kXR_read
//----------------------------------------------------------------------
if( reqId == kXR_readv && msg->GetSize() == 8 )
{
pAsyncMsgSize = dlen;
pReadVRawMsgOffset = 0;
return Take | Raw | RemoveHandler;
}
//----------------------------------------------------------------------
// For everything else we just take what we got
//----------------------------------------------------------------------
return Take | RemoveHandler;
}
//------------------------------------------------------------------------
// kXR_oksofars are special, they are not full responses, so we reset
// the response pointer to 0 and add the message to the partial list
//------------------------------------------------------------------------
case kXR_oksofar:
{
log->Dump( XRootDMsg, "[%s] Got a kXR_oksofar response to request "
"%s", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
pResponse = 0;
pPartialResps.push_back( msg );
//----------------------------------------------------------------------
// For kXR_read we either read in raw mode if the message has not
// been fully reconstructed already, if it has, we adjust
// the buffer offset to prepare for the next one
//----------------------------------------------------------------------
uint16_t reqId = ntohs( req->header.requestid );
if( reqId == kXR_read )
{
if( msg->GetSize() == 8 )
{
pReadRawStarted = false;
pAsyncMsgSize = dlen;
return Take | Raw | NoProcess;
}
else
{
pReadRawCurrentOffset += dlen;
return Take | NoProcess;
}
}
//----------------------------------------------------------------------
// kXR_readv is similar to read, except that the payload is different
//----------------------------------------------------------------------
if( reqId == kXR_readv )
{
if( msg->GetSize() == 8 )
{
pAsyncMsgSize = dlen;
pReadVRawMsgOffset = 0;
return Take | Raw | NoProcess;
}
else
return Take | NoProcess;
}
return Take | NoProcess;
}
//------------------------------------------------------------------------
// Default
//------------------------------------------------------------------------
default:
return Take | RemoveHandler;
}
return Take | RemoveHandler;
}
//----------------------------------------------------------------------------
//! Process the message if it was "taken" by the examine action
//----------------------------------------------------------------------------
void XRootDMsgHandler::Process( Message *msg )
{
Log *log = DefaultEnv::GetLog();
ServerResponse *rsp = (ServerResponse *)msg->GetBuffer();
ClientRequest *req = (ClientRequest *)pRequest->GetBuffer();
//--------------------------------------------------------------------------
// We got an async message
//--------------------------------------------------------------------------
if( rsp->hdr.status == kXR_attn )
{
log->Dump( XRootDMsg, "[%s] Got an async response to message %s, "
"processing it", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
Message *embededMsg = new Message( rsp->hdr.dlen-8 );
embededMsg->Append( msg->GetBuffer( 16 ), rsp->hdr.dlen-8 );
XRDCL_SMART_PTR_T<Message> msgPtr( msg );
pResponse = embededMsg; // this can never happen for oksofars
// we need to unmarshall the header by hand
XRootDTransport::UnMarshallHeader( embededMsg );
//------------------------------------------------------------------------
// Check if the dlen field of the embedded message is consistent with
// the dlen value of the original message
//------------------------------------------------------------------------
ServerResponse *embRsp = (ServerResponse *)embededMsg->GetBuffer();
if( embRsp->hdr.dlen != rsp->hdr.dlen-16 )
{
log->Error( XRootDMsg, "[%s] Sizes of the async response to %s and the "
"embedded message are inconsistent. Expected %d, got %d.",
pUrl.GetHostId().c_str(), pRequest->GetDescription().c_str(),
rsp->hdr.dlen-16, embRsp->hdr.dlen);
pStatus = Status( stFatal, errInvalidMessage );
HandleResponse();
return;
}
Process( embededMsg );
return;
}
//--------------------------------------------------------------------------
// We got an answer, check who we were talking to
//--------------------------------------------------------------------------
AnyObject qryResult;
int *qryResponse = 0;
pPostMaster->QueryTransport( pUrl, XRootDQuery::ServerFlags, qryResult );
qryResult.Get( qryResponse );
pHosts->back().flags = *qryResponse; delete qryResponse; qryResponse = 0;
pPostMaster->QueryTransport( pUrl, XRootDQuery::ProtocolVersion, qryResult );
qryResult.Get( qryResponse );
pHosts->back().protocol = *qryResponse; delete qryResponse;
//--------------------------------------------------------------------------
// Process the message
//--------------------------------------------------------------------------
Status st = XRootDTransport::UnMarshallBody( msg, req->header.requestid );
if( !st.IsOK() )
{
pStatus = Status( stFatal, errInvalidMessage );
HandleResponse();
return;
}
switch( rsp->hdr.status )
{
//------------------------------------------------------------------------
// kXR_ok - we're done here
//------------------------------------------------------------------------
case kXR_ok:
{
log->Dump( XRootDMsg, "[%s] Got a kXR_ok response to request %s",
pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
pStatus = Status();
HandleResponse();
return;
}
//------------------------------------------------------------------------
// kXR_error - we've got a problem
//------------------------------------------------------------------------
case kXR_error:
{
char *errmsg = new char[rsp->hdr.dlen-3]; errmsg[rsp->hdr.dlen-4] = 0;
memcpy( errmsg, rsp->body.error.errmsg, rsp->hdr.dlen-4 );
log->Dump( XRootDMsg, "[%s] Got a kXR_error response to request %s "
"[%d] %s", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str(), rsp->body.error.errnum,
errmsg );
delete [] errmsg;
HandleError( Status(stError, errErrorResponse), pResponse );
return;
}
//------------------------------------------------------------------------
// kXR_redirect - they tell us to go elsewhere
//------------------------------------------------------------------------
case kXR_redirect:
{
XRDCL_SMART_PTR_T<Message> msgPtr( pResponse );
pResponse = 0;
if( rsp->hdr.dlen < 4 )
{
log->Error( XRootDMsg, "[%s] Got invalid redirect response.",
pUrl.GetHostId().c_str() );
pStatus = Status( stError, errInvalidResponse );
HandleResponse();
return;
}
char *urlInfoBuff = new char[rsp->hdr.dlen-3];
urlInfoBuff[rsp->hdr.dlen-4] = 0;
memcpy( urlInfoBuff, rsp->body.redirect.host, rsp->hdr.dlen-4 );
std::string urlInfo = urlInfoBuff;
delete [] urlInfoBuff;
log->Dump( XRootDMsg, "[%s] Got kXR_redirect response to "
"message %s: %s, port %d", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str(), urlInfo.c_str(),
rsp->body.redirect.port );
//----------------------------------------------------------------------
// Check if we can proceed
//----------------------------------------------------------------------
if( !pRedirectCounter )
{
log->Dump( XRootDMsg, "[%s] Redirect limit has been reached for"
"message %s", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
pStatus = Status( stFatal, errRedirectLimit );
HandleResponse();
return;
}
--pRedirectCounter;
//----------------------------------------------------------------------
// Keep the info about this server if we still need to find a load
// balancer
//----------------------------------------------------------------------
if( !pHasLoadBalancer )
{
uint32_t flags = pHosts->back().flags;
if( flags & kXR_isManager )
{
//------------------------------------------------------------------
// If the current server is a meta manager then it supersedes
// any existing load balancer, otherwise we assign a load-balancer
// only if it has not been already assigned
//------------------------------------------------------------------
if( flags & kXR_attrMeta || !pLoadBalancer.url.IsValid() )
{
pLoadBalancer = pHosts->back();
log->Dump( XRootDMsg, "[%s] Current server has been assigned "
"as a load-balancer for message %s",
pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
HostList::iterator it;
for( it = pHosts->begin(); it != pHosts->end(); ++it )
it->loadBalancer = false;
pHosts->back().loadBalancer = true;
}
}
}
//----------------------------------------------------------------------
// Build the URL and check it's validity
//----------------------------------------------------------------------
std::vector<std::string> urlComponents;
std::string newCgi;
Utils::splitString( urlComponents, urlInfo, "?" );
std::ostringstream o;
o << urlComponents[0];
if( rsp->body.redirect.port != -1 )
o << ":" << rsp->body.redirect.port << "/";
URL newUrl = URL( o.str() );
if( !newUrl.IsValid() )
{
pStatus = Status( stError, errInvalidRedirectURL );
log->Error( XRootDMsg, "[%s] Got invalid redirection URL: %s",
pUrl.GetHostId().c_str(), urlInfo.c_str() );
HandleResponse();
return;
}
if( pUrl.GetUserName() != "" && newUrl.GetUserName() == "" )
newUrl.SetUserName( pUrl.GetUserName() );
if( pUrl.GetPassword() != "" && newUrl.GetPassword() == "" )
newUrl.SetPassword( pUrl.GetPassword() );
pUrl = newUrl;
pRedirectUrl = newUrl.GetURL();
URL cgiURL;
if( urlComponents.size() > 1 )
{
std::ostringstream o;
o << "fake://fake:111//fake?";
o << urlComponents[1];
pRedirectUrl += "?";
pRedirectUrl += urlComponents[1];
cgiURL = URL( o.str() );
}
//----------------------------------------------------------------------
// Check if we need to return the URL as a response
//----------------------------------------------------------------------
if( pUrl.GetProtocol() != "root" && pUrl.GetProtocol() != "xroot" )
pRedirectAsAnswer = true;
if( pRedirectAsAnswer )
{
pStatus = Status( stError, errRedirect );
pResponse = msgPtr.release();
HandleResponse();
return;
}
//----------------------------------------------------------------------
// Rewrite the message in a way required to send it to another server
//----------------------------------------------------------------------
Status st = RewriteRequestRedirect( cgiURL.GetParams(),
pUrl.GetPath() );
if( !st.IsOK() )
{
pStatus = st;
HandleResponse();
return;
}
//----------------------------------------------------------------------
// Send the request to the new location
//----------------------------------------------------------------------
pHosts->push_back( pUrl );
pHosts->back().url.SetParams( cgiURL.GetParams() );
HandleError( RetryAtServer(pUrl) );
return;
}
//------------------------------------------------------------------------
// kXR_wait - we wait, and re-issue the request later
//------------------------------------------------------------------------
case kXR_wait:
{
XRDCL_SMART_PTR_T<Message> msgPtr( pResponse );
pResponse = 0;
uint32_t waitSeconds = 0;
if( rsp->hdr.dlen >= 4 )
{
char *infoMsg = new char[rsp->hdr.dlen-3];
infoMsg[rsp->hdr.dlen-4] = 0;
memcpy( infoMsg, rsp->body.wait.infomsg, rsp->hdr.dlen-4 );
log->Dump( XRootDMsg, "[%s] Got kXR_wait response of %d seconds to "
"message %s: %s", pUrl.GetHostId().c_str(),
rsp->body.wait.seconds, pRequest->GetDescription().c_str(),
infoMsg );
delete [] infoMsg;
waitSeconds = rsp->body.wait.seconds;
}
else
{
log->Dump( XRootDMsg, "[%s] Got kXR_wait response of 0 seconds to "
"message %s", pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
}
//----------------------------------------------------------------------
// Some messages require rewriting before they can be sent again
// after wait
//----------------------------------------------------------------------
Status st = RewriteRequestWait();
if( !st.IsOK() )
{
pStatus = st;
HandleResponse();
return;
}
//----------------------------------------------------------------------
// Register a task to resend the message in some seconds, if we still
// have time to do that, and report a timeout otherwise
//----------------------------------------------------------------------
time_t resendTime = ::time(0)+waitSeconds;
if( resendTime < pExpiration )
{
TaskManager *taskMgr = pPostMaster->GetTaskManager();
taskMgr->RegisterTask( new WaitTask( this ), resendTime );
}
else
{
log->Debug( XRootDMsg, "[%s] Wait time is too long, timing out %s",
pUrl.GetHostId().c_str(),
pRequest->GetDescription().c_str() );
pStatus = Status( stError, errOperationExpired );
HandleResponse();
}
return;
}
//------------------------------------------------------------------------
// kXR_waitresp - the response will be returned in some seconds
// as an unsolicited message
//------------------------------------------------------------------------
case kXR_waitresp:
{
XRDCL_SMART_PTR_T<Message> msgPtr( pResponse );
pResponse = 0;
if( rsp->hdr.dlen < 4 )
{
log->Error( XRootDMsg, "[%s] Got invalid waitresp response.",
pUrl.GetHostId().c_str() );
pStatus = Status( stError, errInvalidResponse );
HandleResponse();
return;
}
log->Dump( XRootDMsg, "[%s] Got kXR_waitresp response of %d seconds to "
"message %s", pUrl.GetHostId().c_str(),
rsp->body.waitresp.seconds,
pRequest->GetDescription().c_str() );
return;
}
//------------------------------------------------------------------------
// Default - unrecognized/unsupported response, declare an error
//------------------------------------------------------------------------
default:
{
XRDCL_SMART_PTR_T<Message> msgPtr( pResponse );
pResponse = 0;
log->Dump( XRootDMsg, "[%s] Got unrecognized response %d to "
"message %s", pUrl.GetHostId().c_str(),
rsp->hdr.status, pRequest->GetDescription().c_str() );
pStatus = Status( stError, errInvalidResponse );
HandleResponse();
return;
}
}
return;
}
//----------------------------------------------------------------------------
// Handle an event other that a message arrival - may be timeout
//----------------------------------------------------------------------------
uint8_t XRootDMsgHandler::OnStreamEvent( StreamEvent event,
uint16_t streamNum,
Status status )
{
Log *log = DefaultEnv::GetLog();
log->Dump( XRootDMsg, "[%s] Stream event reported for msg %s",
pUrl.GetHostId().c_str(), pRequest->GetDescription().c_str() );
if( event == Ready )
return 0;
if( streamNum != 0 )
return 0;
HandleError( status, 0 );
return RemoveHandler;
}
//----------------------------------------------------------------------------
// Read message body directly from a socket
//----------------------------------------------------------------------------
Status XRootDMsgHandler::ReadMessageBody( Message *msg,
int socket,
uint32_t &bytesRead )
{
ClientRequest *req = (ClientRequest *)pRequest->GetBuffer();
uint16_t reqId = ntohs( req->header.requestid );
if( reqId == kXR_read )
return ReadRawRead( msg, socket, bytesRead );
if( reqId == kXR_readv )
return ReadRawReadV( msg, socket, bytesRead );
return ReadRawOther( msg, socket, bytesRead );
}
//----------------------------------------------------------------------------
// Handle a kXR_read in raw mode
//----------------------------------------------------------------------------
Status XRootDMsgHandler::ReadRawRead( Message *msg,
int socket,
uint32_t &bytesRead )
{
Log *log = DefaultEnv::GetLog();
//--------------------------------------------------------------------------
// We need to check if we have and overflow, before we start reading
// anything
//--------------------------------------------------------------------------
if( !pReadRawStarted )
{
ChunkInfo chunk = pChunkList->front();
pAsyncOffset = 0;
pAsyncReadSize = pAsyncMsgSize;
pAsyncReadBuffer = ((char*)chunk.buffer)+pReadRawCurrentOffset;
if( pReadRawCurrentOffset + pAsyncMsgSize > chunk.length )
{
log->Error( XRootDMsg, "[%s] Overflow data while reading response to %s"
": expected: %d, got %d bytes",
pUrl.GetHostId().c_str(), pRequest->GetDescription().c_str(),
chunk.length, pReadRawCurrentOffset + pAsyncMsgSize );
pChunkStatus.front().sizeError = true;
pOtherRawStarted = false;
}
else
pReadRawCurrentOffset += pAsyncMsgSize;
pReadRawStarted = true;
}
//--------------------------------------------------------------------------
// If we have an overflow we discard all the incoming data. We do this
// instead of just quitting in order to keep the stream sane.
//--------------------------------------------------------------------------
if( pChunkStatus.front().sizeError )
return ReadRawOther( msg, socket, bytesRead );
//--------------------------------------------------------------------------
// Read the data
//--------------------------------------------------------------------------
return ReadAsync( socket, bytesRead );
}
//----------------------------------------------------------------------------
// Handle a kXR_readv in raw mode
//----------------------------------------------------------------------------
Status XRootDMsgHandler::ReadRawReadV( Message *msg,
int socket,
uint32_t &bytesRead )
{
if( pReadVRawMsgOffset == pAsyncMsgSize )
return Status( stOK, suDone );
Log *log = DefaultEnv::GetLog();
//--------------------------------------------------------------------------
// We've had an error and we are in the discarding mode
//--------------------------------------------------------------------------
if( pReadVRawMsgDiscard )
{
Status st = ReadAsync( socket, bytesRead );
if( st.IsOK() && st.code == suDone )
{
pReadVRawMsgOffset += pAsyncReadSize;
pReadVRawChunkHeaderDone = false;
pReadVRawChunkHeaderStarted = false;
pReadVRawMsgDiscard = false;
delete [] pAsyncReadBuffer;
if( pReadVRawMsgOffset != pAsyncMsgSize )
st.code = suRetry;
log->Dump( XRootDMsg, "[%s] ReadRawReadV: Discarded %d bytes, "
"current offset: %d/%d", pUrl.GetHostId().c_str(),
pAsyncReadSize, pReadVRawMsgOffset, pAsyncMsgSize );
}
return st;
}
//--------------------------------------------------------------------------
// Handle chunk header
//--------------------------------------------------------------------------
if( !pReadVRawChunkHeaderDone )
{
//------------------------------------------------------------------------
// Set up the header reading
//------------------------------------------------------------------------
if( !pReadVRawChunkHeaderStarted )
{
pReadVRawChunkHeaderStarted = true;
//----------------------------------------------------------------------
// We cannot afford to read the next header from the stream because
// we will cross the message boundary
//----------------------------------------------------------------------
if( pReadVRawMsgOffset + 16 > pAsyncMsgSize )
{
uint32_t discardSize = pAsyncMsgSize - pReadVRawMsgOffset;
log->Error( XRootDMsg, "[%s] ReadRawReadV: No enough data to read "
"another chunk header. Discarding %d bytes.",
pUrl.GetHostId().c_str(), discardSize );
pReadVRawMsgDiscard = true;
pAsyncOffset = 0;
pAsyncReadSize = discardSize;
pAsyncReadBuffer = new char[discardSize];
return Status( stOK, suRetry );
}
//----------------------------------------------------------------------
// We set up reading of the next header
//----------------------------------------------------------------------
pAsyncOffset = 0;
pAsyncReadSize = 16;
pAsyncReadBuffer = (char*)&pReadVRawChunkHeader;
}
//------------------------------------------------------------------------
// Do the reading
//------------------------------------------------------------------------
Status st = ReadAsync( socket, bytesRead );
//------------------------------------------------------------------------
// Finalize the header and set everything up for the actual buffer
//------------------------------------------------------------------------
if( st.IsOK() && st.code == suDone )
{
pReadVRawChunkHeaderDone = true;
pReadVRawMsgOffset += 16;
pReadVRawChunkHeader.rlen = ntohl( pReadVRawChunkHeader.rlen );
pReadVRawChunkHeader.offset = ntohll( pReadVRawChunkHeader.offset );
//----------------------------------------------------------------------
// Find the buffer corresponding to the chunk
//----------------------------------------------------------------------
bool chunkFound = false;
for( int i = pReadVRawChunkIndex; i < (int)pChunkList->size(); ++i )
{
if( (*pChunkList)[i].offset == (uint64_t)pReadVRawChunkHeader.offset &&
(*pChunkList)[i].length == (uint32_t)pReadVRawChunkHeader.rlen )
{
chunkFound = true;
pReadVRawChunkIndex = i;
break;
}
}
//----------------------------------------------------------------------
// If the chunk was no found we discard the chunk
//----------------------------------------------------------------------
if( !chunkFound )
{
log->Error( XRootDMsg, "[%s] ReadRawReadV: Impossible to find chunk "
"buffer corresponding to %d bytes at %ld",
pUrl.GetHostId().c_str(), pReadVRawChunkHeader.rlen,
pReadVRawChunkHeader.offset );
uint32_t discardSize = pReadVRawChunkHeader.rlen;
if( pReadVRawMsgOffset + discardSize > pAsyncMsgSize )
discardSize = pAsyncMsgSize - pReadVRawMsgOffset;
pReadVRawMsgDiscard = true;
pAsyncOffset = 0;
pAsyncReadSize = discardSize;
pAsyncReadBuffer = new char[discardSize];
log->Dump( XRootDMsg, "[%s] ReadRawReadV: Discarding %d bytes",
pUrl.GetHostId().c_str(), discardSize );
return Status( stOK, suRetry );
}
//----------------------------------------------------------------------
// The chunk was found, but reading all the data will cross the message
// boundary
//----------------------------------------------------------------------
if( pReadVRawMsgOffset + pReadVRawChunkHeader.rlen > pAsyncMsgSize )
{
uint32_t discardSize = pAsyncMsgSize - pReadVRawMsgOffset;
log->Error( XRootDMsg, "[%s] ReadRawReadV: Malformed chunk header: "
"reading %d bytes from message would cross the message "
"boundary, discarding %d bytes.", pUrl.GetHostId().c_str(),
pReadVRawChunkHeader.rlen, discardSize );
pReadVRawMsgDiscard = true;
pAsyncOffset = 0;
pAsyncReadSize = discardSize;
pAsyncReadBuffer = new char[discardSize];
pChunkStatus[pReadVRawChunkIndex].sizeError = true;
return Status( stOK, suRetry );
}
//----------------------------------------------------------------------
// We're good
//----------------------------------------------------------------------
pAsyncOffset = 0;
pAsyncReadSize = pReadVRawChunkHeader.rlen;
pAsyncReadBuffer = (char*)(*pChunkList)[pReadVRawChunkIndex].buffer;
}
//------------------------------------------------------------------------
// We've seen a reading error
//------------------------------------------------------------------------
if( !st.IsOK() )
return st;
//------------------------------------------------------------------------
// If we are not done reading the header, return back to the event loop.
//------------------------------------------------------------------------
if( st.IsOK() && st.code != suDone )
return st;
}
//--------------------------------------------------------------------------
// Read the body
//--------------------------------------------------------------------------
Status st = ReadAsync( socket, bytesRead );
if( st.IsOK() && st.code == suDone )
{
pReadVRawMsgOffset += pAsyncReadSize;
pReadVRawChunkHeaderDone = false;
pReadVRawChunkHeaderStarted = false;
pChunkStatus[pReadVRawChunkIndex].done = true;
log->Dump( XRootDMsg, "[%s] ReadRawReadV: read buffer for chunk %d@%ld",
pUrl.GetHostId().c_str(),
pReadVRawChunkHeader.rlen, pReadVRawChunkHeader.offset,
pReadVRawMsgOffset, pAsyncMsgSize );
if( pReadVRawMsgOffset < pAsyncMsgSize )
st.code = suRetry;
}
return st;
}
//----------------------------------------------------------------------------
// Handle anything other than kXR_read and kXR_readv in raw mode
//----------------------------------------------------------------------------
Status XRootDMsgHandler::ReadRawOther( Message *msg,
int socket,
uint32_t &bytesRead )
{
if( !pOtherRawStarted )
{
pAsyncOffset = 0;
pAsyncReadSize = pAsyncMsgSize;
pAsyncReadBuffer = new char[pAsyncMsgSize];
pOtherRawStarted = true;
}
Status st = ReadAsync( socket, bytesRead );
if( st.IsOK() && st.code == suRetry )
return st;
delete [] pAsyncReadBuffer;
pAsyncReadBuffer = 0;
pAsyncOffset = pAsyncReadSize = 0;
return st;
}
//--------------------------------------------------------------------------
// Read a buffer asynchronously - depends on pAsyncBuffer, pAsyncSize
// and pAsyncOffset
//--------------------------------------------------------------------------
Status XRootDMsgHandler::ReadAsync( int socket, uint32_t &bytesRead )
{
char *buffer = pAsyncReadBuffer;
buffer += pAsyncOffset;
while( pAsyncOffset < pAsyncReadSize )
{
uint32_t toBeRead = pAsyncReadSize - pAsyncOffset;
int status = ::read( socket, buffer, toBeRead );
if( status < 0 && (errno == EAGAIN || errno == EWOULDBLOCK) )
return Status( stOK, suRetry );
if( status <= 0 )
return Status( stError, errSocketError, errno );
pAsyncOffset += status;
buffer += status;
bytesRead += status;
}
return Status( stOK, suDone );
}
//----------------------------------------------------------------------------
// We're here when we requested sending something over the wire
// and there has been a status update on this action
//----------------------------------------------------------------------------
void XRootDMsgHandler::OnStatusReady( const Message *message,
Status status )
{
Log *log = DefaultEnv::GetLog();
//--------------------------------------------------------------------------
// We were successful, so we now need to listen for a response
//--------------------------------------------------------------------------
if( status.IsOK() )
{
log->Dump( XRootDMsg, "[%s] Message %s has been successfully sent.",
pUrl.GetHostId().c_str(), message->GetDescription().c_str() );
Status st = pPostMaster->Receive( pUrl, this, pExpiration );
if( st.IsOK() )
return;
}
//--------------------------------------------------------------------------
// We have failed, recover if possible
//--------------------------------------------------------------------------
log->Error( XRootDMsg, "[%s] Impossible to send message %s. Trying to "
"recover.", pUrl.GetHostId().c_str(),
message->GetDescription().c_str() );
HandleError( status, 0 );
}
//----------------------------------------------------------------------------
// Are we a raw writer or not?
//----------------------------------------------------------------------------
bool XRootDMsgHandler::IsRaw() const
{
ClientRequest *req = (ClientRequest *)pRequest->GetBuffer();
uint16_t reqId = ntohs( req->header.requestid );
if( reqId == kXR_write )
return true;
return false;
}
//----------------------------------------------------------------------------
// Write the message body
//----------------------------------------------------------------------------
Status XRootDMsgHandler::WriteMessageBody( int socket,
uint32_t &bytesRead )
{
char *buffer = (char*)(*pChunkList)[0].buffer;
uint32_t size = (*pChunkList)[0].length;
uint32_t leftToBeWritten = size-pAsyncOffset;
while( leftToBeWritten )
{
//------------------------------------------------------------------------
// We use send with MSG_NOSIGNAL to avoid SIGPIPEs on Linux
//------------------------------------------------------------------------
#ifdef __linux__
int status = ::send( socket, buffer+pAsyncOffset, leftToBeWritten,
MSG_NOSIGNAL );
#else
int status = ::write( socket, buffer+pAsyncOffset, leftToBeWritten );
#endif
if( status <= 0 )
{
//----------------------------------------------------------------------
// Writing operation would block! So we are done for now, but we will