XRootD
Loading...
Searching...
No Matches
XrdClAsyncSocketHandler.cc
Go to the documentation of this file.
1//------------------------------------------------------------------------------
2// Copyright (c) 2011-2012 by European Organization for Nuclear Research (CERN)
3// Author: Lukasz Janyst <ljanyst@cern.ch>
4//------------------------------------------------------------------------------
5// XRootD is free software: you can redistribute it and/or modify
6// it under the terms of the GNU Lesser General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// XRootD is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU Lesser General Public License
16// along with XRootD. If not, see <http://www.gnu.org/licenses/>.
17//------------------------------------------------------------------------------
18
19#include "XrdCl/XrdClStream.hh"
21#include "XrdCl/XrdClLog.hh"
22#include "XrdCl/XrdClMessage.hh"
27#include "XrdSys/XrdSysE2T.hh"
28#include <netinet/tcp.h>
29
30namespace XrdCl
31{
32 //----------------------------------------------------------------------------
33 // Constructor
34 //----------------------------------------------------------------------------
36 Poller *poller,
37 TransportHandler *transport,
38 AnyObject *channelData,
39 uint16_t subStreamNum,
40 Stream *strm ):
41 pPoller( poller ),
42 pTransport( transport ),
43 pChannelData( channelData ),
44 pSubStreamNum( subStreamNum ),
45 pStream( strm ),
46 pStreamName( ToStreamName( url, subStreamNum ) ),
47 pSocket( new Socket() ),
48 pHandShakeDone( false ),
51 pHSWaitStarted( 0 ),
52 pHSWaitSeconds( 0 ),
53 pUrl( url ),
55 {
56 Env *env = DefaultEnv::GetEnv();
57
58 int timeoutResolution = DefaultTimeoutResolution;
59 env->GetInt( "TimeoutResolution", timeoutResolution );
60 pTimeoutResolution = timeoutResolution;
61
62 pSocket->SetChannelID( pChannelData );
63 pLastActivity = time(0);
64 }
65
66 //----------------------------------------------------------------------------
67 // Destructor
68 //----------------------------------------------------------------------------
74
75 //----------------------------------------------------------------------------
76 // Connect to given address
77 //----------------------------------------------------------------------------
79 {
80 Log *log = DefaultEnv::GetLog();
82 pConnectionTimeout = timeout;
83
84 //--------------------------------------------------------------------------
85 // Initialize the socket
86 //--------------------------------------------------------------------------
87 XRootDStatus st = pSocket->Initialize( pSockAddr.Family() );
88 if( !st.IsOK() )
89 {
90 log->Error( AsyncSockMsg, "[%s] Unable to initialize socket: %s",
91 pStreamName.c_str(), st.ToString().c_str() );
92 st.status = stFatal;
93 return st;
94 }
95
96 //--------------------------------------------------------------------------
97 // Set the keep-alive up
98 //--------------------------------------------------------------------------
99 Env *env = DefaultEnv::GetEnv();
100
101 int keepAlive = DefaultTCPKeepAlive;
102 env->GetInt( "TCPKeepAlive", keepAlive );
103 if( keepAlive )
104 {
105 int param = 1;
106 XRootDStatus st = pSocket->SetSockOpt( SOL_SOCKET, SO_KEEPALIVE, &param,
107 sizeof(param) );
108 if( !st.IsOK() )
109 log->Error( AsyncSockMsg, "[%s] Unable to turn on keepalive: %s",
110 pStreamName.c_str(), st.ToString().c_str() );
111
112#if ( defined(__linux__) || defined(__GNU__) ) && defined( TCP_KEEPIDLE ) && \
113 defined( TCP_KEEPINTVL ) && defined( TCP_KEEPCNT )
114
116 env->GetInt( "TCPKeepAliveTime", param );
117 st = pSocket->SetSockOpt(SOL_TCP, TCP_KEEPIDLE, &param, sizeof(param));
118 if( !st.IsOK() )
119 log->Error( AsyncSockMsg, "[%s] Unable to set keepalive time: %s",
120 pStreamName.c_str(), st.ToString().c_str() );
121
123 env->GetInt( "TCPKeepAliveInterval", param );
124 st = pSocket->SetSockOpt(SOL_TCP, TCP_KEEPINTVL, &param, sizeof(param));
125 if( !st.IsOK() )
126 log->Error( AsyncSockMsg, "[%s] Unable to set keepalive interval: %s",
127 pStreamName.c_str(), st.ToString().c_str() );
128
130 env->GetInt( "TCPKeepAliveProbes", param );
131 st = pSocket->SetSockOpt(SOL_TCP, TCP_KEEPCNT, &param, sizeof(param));
132 if( !st.IsOK() )
133 log->Error( AsyncSockMsg, "[%s] Unable to set keepalive probes: %s",
134 pStreamName.c_str(), st.ToString().c_str() );
135#endif
136 }
137
138 pHandShakeDone = false;
139 pTlsHandShakeOngoing = false;
140 pHSWaitStarted = 0;
141 pHSWaitSeconds = 0;
143
144 //--------------------------------------------------------------------------
145 // Initiate async connection to the address
146 //--------------------------------------------------------------------------
147 char nameBuff[256];
148 pSockAddr.Format( nameBuff, sizeof(nameBuff), XrdNetAddrInfo::fmtAdv6 );
149 log->Debug( AsyncSockMsg, "[%s] Attempting connection to %s",
150 pStreamName.c_str(), nameBuff );
151
152 st = pSocket->ConnectToAddress( pSockAddr, 0 );
153 if( !st.IsOK() )
154 {
155 log->Error( AsyncSockMsg, "[%s] Unable to initiate the connection: %s",
156 pStreamName.c_str(), st.ToString().c_str() );
157 return st;
158 }
159
160 pSocket->SetStatus( Socket::Connecting );
161
162 //--------------------------------------------------------------------------
163 // We should get the ready to write event once we're really connected
164 // so we need to listen to it
165 //--------------------------------------------------------------------------
166 if( !pPoller->AddSocket( pSocket, this ) )
167 {
169 pSocket->Close();
170 return st;
171 }
172
173 if( !pPoller->EnableWriteNotification( pSocket, true, pTimeoutResolution ) )
174 {
176 pPoller->RemoveSocket( pSocket );
177 pSocket->Close();
178 return st;
179 }
180
181 return XRootDStatus();
182 }
183
184 //----------------------------------------------------------------------------
185 // Close the connection
186 //----------------------------------------------------------------------------
188 {
189 Log *log = DefaultEnv::GetLog();
190 log->Debug( AsyncSockMsg, "[%s] Closing the socket", pStreamName.c_str() );
191
192 pTransport->Disconnect( *pChannelData,
194
195 pPoller->RemoveSocket( pSocket );
196 pSocket->Close();
197 return XRootDStatus();
198 }
199
200 std::string AsyncSocketHandler::ToStreamName( const URL &url, uint16_t strmnb )
201 {
202 std::ostringstream o;
203 o << url.GetHostId();
204 o << "." << strmnb;
205 return o.str();
206 }
207
208 //----------------------------------------------------------------------------
209 // Handler a socket event
210 //----------------------------------------------------------------------------
211 void AsyncSocketHandler::Event( uint8_t type, XrdCl::Socket */*socket*/ )
212 {
213 //--------------------------------------------------------------------------
214 // First check if the socket itself wants to apply some mapping on the
215 // event. E.g. in case of TLS socket it might want to map read events to
216 // write events and vice-versa.
217 //--------------------------------------------------------------------------
218 type = pSocket->MapEvent( type );
219
220 //--------------------------------------------------------------------------
221 // Handle any read or write events. If any of the handlers indicate an error
222 // we will have been disconnected. A disconnection may cause the current
223 // object to be asynchronously reused or deleted, so we return immediately.
224 //--------------------------------------------------------------------------
225 if( !EventRead( type ) )
226 return;
227
228 //--------------------------------------------------------------------------
229 // If there's a previosuly noted ECONNRESET error from write we give the
230 // fault now. This gave us the chance to process a read event.
231 //--------------------------------------------------------------------------
232 if( !pReqConnResetError.IsOK() )
233 {
235 return;
236 }
237
238 if( !EventWrite( type ) )
239 return;
240 }
241
242 //----------------------------------------------------------------------------
243 // Handler for read related socket events
244 //----------------------------------------------------------------------------
245 bool AsyncSocketHandler::EventRead( uint8_t type )
246 {
247 //--------------------------------------------------------------------------
248 // Read event
249 //--------------------------------------------------------------------------
250 if( type & ReadyToRead )
251 {
252 pLastActivity = time(0);
254 return OnTLSHandShake();
255
256 if( likely( pHandShakeDone ) )
257 return OnRead();
258
259 return OnReadWhileHandshaking();
260 }
261
262 //--------------------------------------------------------------------------
263 // Read timeout
264 //--------------------------------------------------------------------------
265 else if( type & ReadTimeOut )
266 {
267 if( pHSWaitSeconds )
268 {
269 if( !CheckHSWait() )
270 return false;
271 }
272
273 if( likely( pHandShakeDone ) )
274 return OnReadTimeout();
275
277 }
278
279 return true;
280 }
281
282 //----------------------------------------------------------------------------
283 // Handler for write related socket events
284 //----------------------------------------------------------------------------
286 {
287 //--------------------------------------------------------------------------
288 // Write event
289 //--------------------------------------------------------------------------
290 if( type & ReadyToWrite )
291 {
292 pLastActivity = time(0);
293 if( unlikely( pSocket->GetStatus() == Socket::Connecting ) )
294 return OnConnectionReturn();
295
296 //------------------------------------------------------------------------
297 // Make sure we are not writing anything if we have been told to wait.
298 //------------------------------------------------------------------------
299 if( pHSWaitSeconds != 0 )
300 return true;
301
303 return OnTLSHandShake();
304
305 if( likely( pHandShakeDone ) )
306 return OnWrite();
307
309 }
310
311 //--------------------------------------------------------------------------
312 // Write timeout
313 //--------------------------------------------------------------------------
314 else if( type & WriteTimeOut )
315 {
316 if( likely( pHandShakeDone ) )
317 return OnWriteTimeout();
318
320 }
321
322 return true;
323 }
324
325 //----------------------------------------------------------------------------
326 // Connect returned
327 //----------------------------------------------------------------------------
329 {
330 //--------------------------------------------------------------------------
331 // Check whether we were able to connect
332 //--------------------------------------------------------------------------
333 Log *log = DefaultEnv::GetLog();
334 log->Debug( AsyncSockMsg, "[%s] Async connection call returned",
335 pStreamName.c_str() );
336
337 int errorCode = 0;
338 socklen_t optSize = sizeof( errorCode );
339 XRootDStatus st = pSocket->GetSockOpt( SOL_SOCKET, SO_ERROR, &errorCode,
340 &optSize );
341
342 //--------------------------------------------------------------------------
343 // This is an internal error really (either logic or system fault),
344 // so we call it a day and don't retry
345 //--------------------------------------------------------------------------
346 if( !st.IsOK() )
347 {
348 log->Error( AsyncSockMsg, "[%s] Unable to get the status of the "
349 "connect operation: %s", pStreamName.c_str(),
350 XrdSysE2T( errno ) );
351 pStream->OnConnectError( pSubStreamNum,
353 return false;
354 }
355
356 //--------------------------------------------------------------------------
357 // We were unable to connect
358 //--------------------------------------------------------------------------
359 if( errorCode )
360 {
361 log->Error( AsyncSockMsg, "[%s] Unable to connect: %s",
362 pStreamName.c_str(), XrdSysE2T( errorCode ) );
363 pStream->OnConnectError( pSubStreamNum,
365 return false;
366 }
367 pSocket->SetStatus( Socket::Connected );
368
369 //--------------------------------------------------------------------------
370 // Cork the socket
371 //--------------------------------------------------------------------------
372 st = pSocket->Cork();
373 if( !st.IsOK() )
374 {
375 pStream->OnConnectError( pSubStreamNum, st );
376 return false;
377 }
378
379 //--------------------------------------------------------------------------
380 // Initialize the handshake
381 //--------------------------------------------------------------------------
382 pHandShakeData.reset( new HandShakeData( pStream->GetURL(),
383 pSubStreamNum ) );
384 pHandShakeData->serverAddr = pSocket->GetServerAddress();
385 pHandShakeData->clientName = pSocket->GetSockName();
386 pHandShakeData->streamName = pStreamName;
387
388 st = pTransport->HandShake( pHandShakeData.get(), *pChannelData );
389 if( !st.IsOK() )
390 {
391 log->Error( AsyncSockMsg, "[%s] Connection negotiation failed",
392 pStreamName.c_str() );
393 pStream->OnConnectError( pSubStreamNum, st );
394 return false;
395 }
396
397 if( st.code != suRetry )
398 ++pHandShakeData->step;
399
400 //--------------------------------------------------------------------------
401 // Initialize the hand-shake reader and writer
402 //--------------------------------------------------------------------------
403 hswriter.reset( new AsyncHSWriter( *pSocket, pStreamName ) );
405
406 //--------------------------------------------------------------------------
407 // Transport has given us something to send
408 //--------------------------------------------------------------------------
409 if( pHandShakeData->out )
410 {
411 hswriter->Reset( pHandShakeData->out );
412 pHandShakeData->out = nullptr;
413 }
414
415 //--------------------------------------------------------------------------
416 // Listen to what the server has to say
417 //--------------------------------------------------------------------------
418 if( !pPoller->EnableReadNotification( pSocket, true, pTimeoutResolution ) )
419 {
420 pStream->OnConnectError( pSubStreamNum,
422 return false;
423 }
424 return true;
425 }
426
427 //----------------------------------------------------------------------------
428 // Got a write readiness event
429 //----------------------------------------------------------------------------
431 {
432 if( !reqwriter )
433 {
434 OnFault( XRootDStatus( stError, errInternal, 0, "Request writer is null." ) );
435 return false;
436 }
437 //--------------------------------------------------------------------------
438 // Let's do the writing ...
439 //--------------------------------------------------------------------------
440 XRootDStatus st = reqwriter->Write();
441
442 //--------------------------------------------------------------------------
443 // In the case of ECONNRESET perhaps the server sent us something.
444 // To give a chance to read it in the next event poll we pass this as a
445 // retry, but return the error after the next event.
446 //--------------------------------------------------------------------------
447 if( st.code == errSocketError && st.errNo == ECONNRESET )
448 {
449 if( (DisableUplink()).IsOK() )
450 {
452 st = XRootDStatus( stOK, suRetry );
453 }
454 }
455 if( !st.IsOK() )
456 {
457 //------------------------------------------------------------------------
458 // We failed
459 //------------------------------------------------------------------------
460 OnFault( st );
461 return false;
462 }
463 //--------------------------------------------------------------------------
464 // We are not done yet
465 //--------------------------------------------------------------------------
466 if( st.code == suRetry) return true;
467 //--------------------------------------------------------------------------
468 // Disable the respective substream if empty
469 //--------------------------------------------------------------------------
470 reqwriter->Reset();
471 pStream->DisableIfEmpty( pSubStreamNum );
472 return true;
473 }
474
475 //----------------------------------------------------------------------------
476 // Got a write readiness event while handshaking
477 //----------------------------------------------------------------------------
479 {
480 XRootDStatus st;
481 if( !hswriter || !hswriter->HasMsg() )
482 {
483 if( !(st = DisableUplink()).IsOK() )
484 {
486 return false;
487 }
488 return true;
489 }
490 //--------------------------------------------------------------------------
491 // Let's do the writing ...
492 //--------------------------------------------------------------------------
493 st = hswriter->Write();
494 if( !st.IsOK() )
495 {
496 //------------------------------------------------------------------------
497 // We failed
498 //------------------------------------------------------------------------
500 return false;
501 }
502 //--------------------------------------------------------------------------
503 // We are not done yet
504 //--------------------------------------------------------------------------
505 if( st.code == suRetry ) return true;
506 //--------------------------------------------------------------------------
507 // Disable the uplink
508 // Note: at this point we don't deallocate the HS message as we might need
509 // to re-send it in case of a kXR_wait response
510 //--------------------------------------------------------------------------
511 if( !(st = DisableUplink()).IsOK() )
512 {
514 return false;
515 }
516 return true;
517 }
518
519 //----------------------------------------------------------------------------
520 // Got a read readiness event
521 //----------------------------------------------------------------------------
523 {
524 //--------------------------------------------------------------------------
525 // Make sure the response reader object exists
526 //--------------------------------------------------------------------------
527 if( !rspreader )
528 {
529 OnFault( XRootDStatus( stError, errInternal, 0, "Response reader is null." ) );
530 return false;
531 }
532
533 //--------------------------------------------------------------------------
534 // Readout the data from the socket
535 //--------------------------------------------------------------------------
536 XRootDStatus st = rspreader->Read();
537
538 //--------------------------------------------------------------------------
539 // Handler header corruption
540 //--------------------------------------------------------------------------
541 if( !st.IsOK() && st.code == errCorruptedHeader )
542 {
544 return false;
545 }
546
547 //--------------------------------------------------------------------------
548 // Handler other errors
549 //--------------------------------------------------------------------------
550 if( !st.IsOK() )
551 {
552 OnFault( st );
553 return false;
554 }
555
556 //--------------------------------------------------------------------------
557 // We are not done yet
558 //--------------------------------------------------------------------------
559 if( st.code == suRetry ) return true;
560
561 //--------------------------------------------------------------------------
562 // We are done, reset the response reader so we can read out next message
563 //--------------------------------------------------------------------------
564 rspreader->Reset();
565 return true;
566 }
567
568 //----------------------------------------------------------------------------
569 // Got a read readiness event while handshaking
570 //----------------------------------------------------------------------------
572 {
573 //--------------------------------------------------------------------------
574 // Make sure the response reader object exists
575 //--------------------------------------------------------------------------
576 if( !hsreader )
577 {
578 OnFault( XRootDStatus( stError, errInternal, 0, "Hand-shake reader is null." ) );
579 return false;
580 }
581
582 //--------------------------------------------------------------------------
583 // Read the message and let the transport handler look at it when
584 // reading has finished
585 //--------------------------------------------------------------------------
586 XRootDStatus st = hsreader->Read();
587 if( !st.IsOK() )
588 {
590 return false;
591 }
592
593 if( st.code != suDone )
594 return true;
595
596 return HandleHandShake( hsreader->ReleaseMsg() );
597 }
598
599 //------------------------------------------------------------------------
600 // Handle the handshake message
601 //------------------------------------------------------------------------
602 bool AsyncSocketHandler::HandleHandShake( std::unique_ptr<Message> msg )
603 {
604 //--------------------------------------------------------------------------
605 // OK, we have a new message, let's deal with it;
606 //--------------------------------------------------------------------------
607 pHandShakeData->in = msg.release();
608 XRootDStatus st = pTransport->HandShake( pHandShakeData.get(), *pChannelData );
609
610 //--------------------------------------------------------------------------
611 // Deal with wait responses
612 //--------------------------------------------------------------------------
613 kXR_int32 waitSeconds = HandleWaitRsp( pHandShakeData->in );
614
615 delete pHandShakeData->in;
616 pHandShakeData->in = 0;
617
618 if( !st.IsOK() )
619 {
621 return false;
622 }
623
624 if( st.code == suRetry )
625 {
626 //------------------------------------------------------------------------
627 // We are handling a wait response and the transport handler told
628 // as to retry the request
629 //------------------------------------------------------------------------
630 if( waitSeconds >=0 )
631 {
632 time_t resendTime = ::time( 0 ) + waitSeconds;
633 if( resendTime > pConnectionStarted + pConnectionTimeout )
634 {
635 Log *log = DefaultEnv::GetLog();
636 log->Error( AsyncSockMsg,
637 "[%s] Won't retry kXR_endsess request because would"
638 "reach connection timeout.",
639 pStreamName.c_str() );
640
642 return false;
643 }
644 else
645 {
646 //--------------------------------------------------------------------
647 // We need to wait before replaying the request
648 //--------------------------------------------------------------------
649 Log *log = DefaultEnv::GetLog();
650 log->Debug( AsyncSockMsg, "[%s] Received a wait response to endsess request, "
651 "will wait for %d seconds before replaying the endsess request",
652 pStreamName.c_str(), waitSeconds );
653 pHSWaitStarted = time( 0 );
654 pHSWaitSeconds = waitSeconds;
655 }
656 return true;
657 }
658 //------------------------------------------------------------------------
659 // We are re-sending a protocol request
660 //------------------------------------------------------------------------
661 else if( pHandShakeData->out )
662 {
663 return SendHSMsg();
664 }
665 }
666
667 //--------------------------------------------------------------------------
668 // If now is the time to enable encryption
669 //--------------------------------------------------------------------------
670 if( !pSocket->IsEncrypted() &&
671 pTransport->NeedEncryption( pHandShakeData.get(), *pChannelData ) )
672 {
674 if( !st.IsOK() )
675 return false;
676 if ( st.code == suRetry )
677 return true;
678 }
679
680 //--------------------------------------------------------------------------
681 // Now prepare the next step of the hand-shake procedure
682 //--------------------------------------------------------------------------
683 return HandShakeNextStep( st.IsOK() && st.code == suDone );
684 }
685
686 //------------------------------------------------------------------------
687 // Prepare the next step of the hand-shake procedure
688 //------------------------------------------------------------------------
690 {
691 //--------------------------------------------------------------------------
692 // We successfully proceeded to the next step
693 //--------------------------------------------------------------------------
694 ++pHandShakeData->step;
695
696 //--------------------------------------------------------------------------
697 // The hand shake process is done
698 //--------------------------------------------------------------------------
699 if( done )
700 {
701 pHandShakeData.reset();
702 hswriter.reset();
703 hsreader.reset();
704 //------------------------------------------------------------------------
705 // Initialize the request writer & reader
706 //------------------------------------------------------------------------
709 XRootDStatus st;
710 if( !(st = EnableUplink()).IsOK() )
711 {
713 return false;
714 }
715 pHandShakeDone = true;
716 pStream->OnConnect( pSubStreamNum );
717 }
718 //--------------------------------------------------------------------------
719 // The transport handler gave us something to write
720 //--------------------------------------------------------------------------
721 else if( pHandShakeData->out )
722 {
723 return SendHSMsg();
724 }
725 return true;
726 }
727
728 //----------------------------------------------------------------------------
729 // Handle fault
730 //----------------------------------------------------------------------------
732 {
733 Log *log = DefaultEnv::GetLog();
734 log->Error( AsyncSockMsg, "[%s] Socket error encountered: %s",
735 pStreamName.c_str(), st.ToString().c_str() );
736
737 pStream->OnError( pSubStreamNum, st );
738 }
739
740 //----------------------------------------------------------------------------
741 // Handle fault while handshaking
742 //----------------------------------------------------------------------------
744 {
745 Log *log = DefaultEnv::GetLog();
746 log->Error( AsyncSockMsg, "[%s] Socket error while handshaking: %s",
747 pStreamName.c_str(), st.ToString().c_str() );
748
749 pStream->OnConnectError( pSubStreamNum, st );
750 }
751
752 //----------------------------------------------------------------------------
753 // Handle write timeout
754 //----------------------------------------------------------------------------
756 {
757 return pStream->OnWriteTimeout( pSubStreamNum );
758 }
759
760 //----------------------------------------------------------------------------
761 // Handler read timeout
762 //----------------------------------------------------------------------------
764 {
765 return pStream->OnReadTimeout( pSubStreamNum );
766 }
767
768 //----------------------------------------------------------------------------
769 // Handle timeout while handshaking
770 //----------------------------------------------------------------------------
772 {
773 time_t now = time(0);
775 {
777 return false;
778 }
779 return true;
780 }
781
782 //----------------------------------------------------------------------------
783 // Handle header corruption in case of kXR_status response
784 //----------------------------------------------------------------------------
786 {
787 //--------------------------------------------------------------------------
788 // We need to force a socket error so this is handled in a similar way as
789 // a stream t/o and all requests are retried
790 //--------------------------------------------------------------------------
791 pStream->ForceError( XRootDStatus( stError, errSocketError ) );
792 }
793
794 //----------------------------------------------------------------------------
795 // Carry out the TLS hand-shake
796 //----------------------------------------------------------------------------
798 {
799 Log *log = DefaultEnv::GetLog();
800 log->Debug( AsyncSockMsg, "[%s] TLS hand-shake exchange.", pStreamName.c_str() );
801
802 XRootDStatus st;
803 if( !( st = pSocket->TlsHandShake( this, pUrl.GetHostName() ) ).IsOK() )
804 {
805 pTlsHandShakeOngoing = false;
807 return st;
808 }
809
810 if( st.code == suRetry )
811 {
813 return st;
814 }
815
816 pTlsHandShakeOngoing = false;
817 log->Info( AsyncSockMsg, "[%s] TLS hand-shake done.", pStreamName.c_str() );
818
819 return st;
820 }
821
822 //----------------------------------------------------------------------------
823 // Handle read/write event if we are in the middle of a TLS hand-shake
824 //----------------------------------------------------------------------------
826 {
828 if( !st.IsOK() )
829 return false;
830 if ( st.code == suRetry )
831 return true;
832
833 return HandShakeNextStep( pTransport->HandShakeDone( pHandShakeData.get(),
834 *pChannelData ) );
835 }
836
837 //----------------------------------------------------------------------------
838 // Prepare a HS writer for sending and enable uplink
839 //----------------------------------------------------------------------------
841 {
842 if( !hswriter )
843 {
845 "HS writer object missing!" ) );
846 return false;
847 }
848 //--------------------------------------------------------------------------
849 // We only set a new HS message if this is not a replay due to kXR_wait
850 //--------------------------------------------------------------------------
851 if( !pHSWaitSeconds )
852 {
853 hswriter->Reset( pHandShakeData->out );
854 pHandShakeData->out = nullptr;
855 }
856 //--------------------------------------------------------------------------
857 // otherwise we replay the kXR_endsess request
858 //--------------------------------------------------------------------------
859 else
860 hswriter->Replay();
861 //--------------------------------------------------------------------------
862 // Enable writing so we can replay the HS message
863 //--------------------------------------------------------------------------
864 XRootDStatus st;
865 if( !(st = EnableUplink()).IsOK() )
866 {
868 return false;
869 }
870 return true;
871 }
872
874 {
875 // It would be more coherent if this could be done in the
876 // transport layer, unfortunately the API does not allow it.
877 kXR_int32 waitSeconds = -1;
879 if( rsp->hdr.status == kXR_wait )
880 waitSeconds = rsp->body.wait.seconds;
881 return waitSeconds;
882 }
883
884 //----------------------------------------------------------------------------
885 // Check if HS wait time elapsed
886 //----------------------------------------------------------------------------
888 {
889 time_t now = time( 0 );
890 if( now - pHSWaitStarted >= pHSWaitSeconds )
891 {
892 Log *log = DefaultEnv::GetLog();
893 log->Debug( AsyncSockMsg, "[%s] The hand-shake wait time elapsed, will "
894 "replay the endsess request.", pStreamName.c_str() );
895 if( !SendHSMsg() )
896 return false;
897 //------------------------------------------------------------------------
898 // Make sure the wait state is reset
899 //------------------------------------------------------------------------
900 pHSWaitSeconds = 0;
901 pHSWaitStarted = 0;
902 }
903 return true;
904 }
905
906 //------------------------------------------------------------------------
907 // Get the IP stack
908 //------------------------------------------------------------------------
910 {
911 std::string ipstack( ( pSockAddr.isIPType( XrdNetAddr::IPType::IPv6 ) &&
912 !pSockAddr.isMapped() ) ? "IPv6" : "IPv4" );
913 return ipstack;
914 }
915
916 //------------------------------------------------------------------------
917 // Get IP address
918 //------------------------------------------------------------------------
920 {
921 char nameBuff[256];
922 pSockAddr.Format( nameBuff, sizeof(nameBuff), XrdNetAddrInfo::fmtAddr, XrdNetAddrInfo::noPort );
923 return nameBuff;
924 }
925
926 //------------------------------------------------------------------------
928 //------------------------------------------------------------------------
930 {
931 const char *cstr = pSockAddr.Name();
932 if( !cstr )
933 return std::string();
934 return cstr;
935 }
936}
union ServerResponse::@040373375333017131300127053271011057331004327334 body
@ kXR_wait
Definition XProtocol.hh:905
ServerResponseHeader hdr
int kXR_int32
Definition XPtypes.hh:89
#define likely(x)
#define unlikely(x)
const char * XrdSysE2T(int errcode)
Definition XrdSysE2T.cc:104
Utility class encapsulating reading hand-shake response logic.
Utility class encapsulating writing hand-shake request logic.
Utility class encapsulating reading response message logic.
Utility class encapsulating writing request logic.
static std::string ToStreamName(const URL &url, uint16_t strmnb)
Convert Stream object and sub-stream number to stream name.
bool OnReadTimeout() XRD_WARN_UNUSED_RESULT
std::unique_ptr< AsyncHSWriter > hswriter
virtual bool OnConnectionReturn() XRD_WARN_UNUSED_RESULT
bool OnWriteTimeout() XRD_WARN_UNUSED_RESULT
bool OnWrite() XRD_WARN_UNUSED_RESULT
bool OnTimeoutWhileHandshaking() XRD_WARN_UNUSED_RESULT
bool CheckHSWait() XRD_WARN_UNUSED_RESULT
bool EventRead(uint8_t type) XRD_WARN_UNUSED_RESULT
std::unique_ptr< AsyncHSReader > hsreader
bool HandleHandShake(std::unique_ptr< Message > msg) XRD_WARN_UNUSED_RESULT
bool OnWriteWhileHandshaking() XRD_WARN_UNUSED_RESULT
XRootDStatus Close()
Close the connection.
void OnFaultWhileHandshaking(XRootDStatus st)
virtual void Event(uint8_t type, XrdCl::Socket *)
Handle a socket event.
kXR_int32 HandleWaitRsp(Message *rsp)
bool HandShakeNextStep(bool done) XRD_WARN_UNUSED_RESULT
bool OnReadWhileHandshaking() XRD_WARN_UNUSED_RESULT
std::unique_ptr< AsyncMsgWriter > reqwriter
XRootDStatus EnableUplink()
Enable uplink.
std::string GetIpStack() const
Get the IP stack.
bool EventWrite(uint8_t type) XRD_WARN_UNUSED_RESULT
std::string GetHostName()
Get hostname.
std::unique_ptr< AsyncMsgReader > rspreader
XRootDStatus DisableUplink()
Disable uplink.
std::unique_ptr< HandShakeData > pHandShakeData
bool OnRead() XRD_WARN_UNUSED_RESULT
XRootDStatus Connect(time_t timeout)
Connect to the currently set address.
AsyncSocketHandler(const URL &url, Poller *poller, TransportHandler *transport, AnyObject *channelData, uint16_t subStreamNum, Stream *strm)
Constructor.
bool OnTLSHandShake() XRD_WARN_UNUSED_RESULT
bool SendHSMsg() XRD_WARN_UNUSED_RESULT
std::string GetIpAddr()
Get IP address.
const char * GetBuffer(uint32_t offset=0) const
Get the message buffer.
static Log * GetLog()
Get default log.
static Env * GetEnv()
Get default client environment.
bool GetInt(const std::string &key, int &value)
Definition XrdClEnv.cc:89
Handle diagnostics.
Definition XrdClLog.hh:101
void Error(uint64_t topic, const char *format,...)
Report an error.
Definition XrdClLog.cc:231
void Info(uint64_t topic, const char *format,...)
Print an info.
Definition XrdClLog.cc:265
void Debug(uint64_t topic, const char *format,...)
Print a debug message.
Definition XrdClLog.cc:282
The message representation used throughout the system.
Interface for socket pollers.
@ ReadTimeOut
Read timeout.
@ ReadyToWrite
Writing won't block.
@ WriteTimeOut
Write timeout.
@ ReadyToRead
New data has arrived.
A network socket.
@ Connected
The socket is connected.
@ Connecting
The connection process is in progress.
Perform the handshake and the authentication for each physical stream.
URL representation.
Definition XrdClURL.hh:31
std::string GetHostId() const
Get the host part of the URL (user:password@host:port)
Definition XrdClURL.hh:99
static const int noPort
Do not add port number.
@ fmtAddr
Address using suitable ipv4 or ipv6 format.
const uint16_t suRetry
const uint16_t errSocketOptError
const int DefaultTCPKeepAliveProbes
const uint16_t stFatal
Fatal error, it's still an error.
const uint16_t errPollerError
const uint16_t stError
An error occurred that could potentially be retried.
const uint16_t errSocketTimeout
const uint16_t errInternal
Internal error.
const uint16_t stOK
Everything went OK.
const int DefaultTimeoutResolution
const uint64_t AsyncSockMsg
const int DefaultTCPKeepAliveInterval
const int DefaultTCPKeepAlive
const uint16_t errConnectionError
const int DefaultTCPKeepAliveTime
const uint16_t errSocketError
const uint16_t errCorruptedHeader
const uint16_t suDone
Data structure that carries the handshake information.
uint16_t code
Error type, or additional hints on what to do.
uint16_t status
Status of the execution.
bool IsOK() const
We're fine.
std::string ToString() const
Create a string representation.
uint32_t errNo
Errno, if any.