Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TSocket.cxx
Go to the documentation of this file.
1// @(#)root/net:$Id$
2// Author: Fons Rademakers 18/12/96
3
4/*************************************************************************
5 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12/**
13\file TSocket.cxx
14\class TSocket
15\brief This class implements client sockets.
16\note This class deals with sockets: the user is entirely responsible for the security of their usage, for example, but
17not limited to, the management of the connections to said sockets.
18
19A socket is an endpoint for communication between two machines. The actual work is done via the TSystem class (either
20TUnixSystem or TWinNTSystem).
21
22**/
23
24#include "Bytes.h"
25#include "Compression.h"
26#define ROOT_NetErrors_cxx
27#include "NetErrors.h"
28#include "TError.h"
29#include "TMessage.h"
30#include "TObjString.h"
31#include "TPSocket.h"
32#include "TPluginManager.h"
33#include "TROOT.h"
34#include "TString.h"
35#include "TSystem.h"
36#include "TUrl.h"
37#include "TStreamerInfo.h"
38#include "TProcessID.h"
39
40#include <limits>
41
44
45//
46// Client "protocol changes"
47//
48// This was in TNetFile and TAuthenticate before, but after the introduction
49// of TSocket::CreateAuthSocket the common place for all the clients is TSocket,
50// so this seems to be the right place for a version number
51//
52// 7: added support for ReOpen(), kROOTD_BYE and kROOTD_PROTOCOL2
53// 8: added support for update being a create (open stat = 2 and not 1)
54// 9: added new authentication features (see README.AUTH)
55// 10: added support for authenticated socket via TSocket::CreateAuthSocket(...)
56// 11: modified SSH protocol + support for server 'no authentication' mode
57// 12: add random tags to avoid reply attacks (password+token)
58// 13: LEGACY: authentication re-organization; cleanup in PROOF
59// 14: support for SSH authentication via SSH tunnel
60// 15: cope with fixes in TUrl::GetFile
61// 16: add env setup message exchange
62//
63Int_t TSocket::fgClientProtocol = 17; // increase when client protocol changes
64
65////////////////////////////////////////////////////////////////////////////////
66/// Create a socket. Connect to the named service at address addr.
67/// Use tcpwindowsize to specify the size of the receive buffer, it has
68/// to be specified here to make sure the window scale option is set (for
69/// tcpwindowsize > 65KB and for platforms supporting window scaling).
70/// Returns when connection has been accepted by remote side. Use IsValid()
71/// to check the validity of the socket. Every socket is added to the TROOT
72/// sockets list which will make sure that any open sockets are properly
73/// closed on program termination.
74
76 : TNamed(addr.GetHostName(), service), fCompress(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal)
77{
80
84 if (fService.Contains("root"))
86 fAddress = addr;
88 fBytesSent = 0;
89 fBytesRecv = 0;
91 fUUIDs = 0;
92 fLastUsageMtx = 0;
94
95 if (fAddress.GetPort() != -1) {
98
99 if (fSocket != kInvalid) {
100 gROOT->GetListOfSockets()->Add(this);
101 }
102 } else
104
105}
106
107////////////////////////////////////////////////////////////////////////////////
108/// Create a socket. Connect to the specified port # at address addr.
109/// Use tcpwindowsize to specify the size of the receive buffer, it has
110/// to be specified here to make sure the window scale option is set (for
111/// tcpwindowsize > 65KB and for platforms supporting window scaling).
112/// Returns when connection has been accepted by remote side. Use IsValid()
113/// to check the validity of the socket. Every socket is added to the TROOT
114/// sockets list which will make sure that any open sockets are properly
115/// closed on program termination.
116
118 : TNamed(addr.GetHostName(), ""), fCompress(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal)
119{
122
124 fRemoteProtocol= -1;
126 if (fService.Contains("root"))
128 fAddress = addr;
131 fBytesSent = 0;
132 fBytesRecv = 0;
134 fUUIDs = 0;
135 fLastUsageMtx = 0;
137
140 if (fSocket == kInvalid)
141 fAddress.fPort = -1;
142 else {
143 gROOT->GetListOfSockets()->Add(this);
144 }
145}
146
147////////////////////////////////////////////////////////////////////////////////
148/// Create a socket. Connect to named service on the remote host.
149/// Use tcpwindowsize to specify the size of the receive buffer, it has
150/// to be specified here to make sure the window scale option is set (for
151/// tcpwindowsize > 65KB and for platforms supporting window scaling).
152/// Returns when connection has been accepted by remote side. Use IsValid()
153/// to check the validity of the socket. Every socket is added to the TROOT
154/// sockets list which will make sure that any open sockets are properly
155/// closed on program termination.
156
158 : TNamed(host, service), fCompress(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal)
159{
162
164 fRemoteProtocol= -1;
166 if (fService.Contains("root"))
171 fBytesSent = 0;
172 fBytesRecv = 0;
174 fUUIDs = 0;
175 fLastUsageMtx = 0;
177
178 if (fAddress.GetPort() != -1) {
180 if (fSocket != kInvalid) {
181 gROOT->GetListOfSockets()->Add(this);
182 }
183 } else
185}
186
187////////////////////////////////////////////////////////////////////////////////
188/// Create a socket. The url parameter has the form
189///
190/// [sockd://]host[:port][/service]
191///
192/// where
193/// [port] = is the remote port number
194/// [service] = service name used to determine the port
195/// (for backward compatibility, specification of
196/// port as priority)
197///
198/// Connect to the specified port # on the remote host.
199/// Use tcpwindowsize to specify the size of the receive buffer, it has
200/// to be specified here to make sure the window scale option is set (for
201/// tcpwindowsize > 65KB and for platforms supporting window scaling).
202/// Returns when connection has been accepted by remote side. Use IsValid()
203/// to check the validity of the socket. Every socket is added to the TROOT
204/// sockets list which will make sure that any open sockets are properly
205/// closed on program termination.
206
208 : TNamed(TUrl(url).GetHost(), ""), fCompress(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal)
209{
212
213 fUrl = TString(url);
214 TString host(TUrl(fUrl).GetHost());
215
217 fRemoteProtocol= -1;
219 if (fUrl.Contains("root"))
225 fBytesSent = 0;
226 fBytesRecv = 0;
228 fUUIDs = 0;
229 fLastUsageMtx = 0;
231
233 if (fSocket == kInvalid) {
235 } else {
236 gROOT->GetListOfSockets()->Add(this);
237 }
238}
239
240////////////////////////////////////////////////////////////////////////////////
241/// Create a socket in the Unix domain on 'sockpath'.
242/// Returns when connection has been accepted by the server. Use IsValid()
243/// to check the validity of the socket. Every socket is added to the TROOT
244/// sockets list which will make sure that any open sockets are properly
245/// closed on program termination.
246
248 fCompress(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal)
249{
252
253 fUrl = sockpath;
254
255 fService = "unix";
256 fRemoteProtocol= -1;
258 fAddress.fPort = -1;
259 fName.Form("unix:%s", sockpath);
261 fBytesSent = 0;
262 fBytesRecv = 0;
263 fTcpWindowSize = -1;
264 fUUIDs = 0;
265 fLastUsageMtx = 0;
267
269 if (fSocket > 0) {
270 gROOT->GetListOfSockets()->Add(this);
271 }
272}
273
274////////////////////////////////////////////////////////////////////////////////
275/// Create a socket. The socket will adopt previously opened TCP socket with
276/// descriptor desc.
277
278TSocket::TSocket(Int_t desc) : TNamed("", ""), fCompress(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal)
279{
282
283 fRemoteProtocol = 0;
284 fService = (char *)kSOCKD;
286 fBytesSent = 0;
287 fBytesRecv = 0;
288 fTcpWindowSize = -1;
289 fUUIDs = 0;
290 fLastUsageMtx = 0;
292
293 if (desc >= 0) {
294 fSocket = desc;
296 gROOT->GetListOfSockets()->Add(this);
297 } else
299}
300
301////////////////////////////////////////////////////////////////////////////////
302/// Create a socket. The socket will adopt previously opened Unix socket with
303/// descriptor desc. The sockpath arg is for info purposes only. Use
304/// this method to adopt e.g. a socket created via socketpair().
305
307 fCompress(ROOT::RCompressionSetting::EAlgorithm::kUseGlobal)
308{
311
312 fUrl = sockpath;
313
314 fService = "unix";
315 fRemoteProtocol= -1;
317 fAddress.fPort = -1;
318 fName.Form("unix:%s", sockpath);
320 fBytesSent = 0;
321 fBytesRecv = 0;
322 fTcpWindowSize = -1;
323 fUUIDs = 0;
324 fLastUsageMtx = 0;
326
327 if (desc >= 0) {
328 fSocket = desc;
329 gROOT->GetListOfSockets()->Add(this);
330 } else
332}
333
334
335////////////////////////////////////////////////////////////////////////////////
336/// TSocket copy ctor.
337
339{
340 fSocket = s.fSocket;
341 fService = s.fService;
342 fAddress = s.fAddress;
350 fUUIDs = 0;
351 fLastUsageMtx = 0;
353
354 if (fSocket != kInvalid) {
355 gROOT->GetListOfSockets()->Add(this);
356 }
357}
358////////////////////////////////////////////////////////////////////////////////
359/// Close the socket and mark as due to a broken connection.
360
372
373////////////////////////////////////////////////////////////////////////////////
374/// Close the socket. If option is "force", calls shutdown(id,2) to
375/// shut down the connection. This will close the connection also
376/// for the parent of this process. Also called via the dtor (without
377/// option "force", call explicitly Close("force") if this is desired).
378
380{
381 Bool_t force = option ? (!strcmp(option, "force") ? kTRUE : kFALSE) : kFALSE;
382
383 if (fSocket != kInvalid) {
384 if (IsValid()) { // Filter out kInvalidStillInList case (disconnected but not removed from list)
386 }
387 gROOT->GetListOfSockets()->Remove(this);
388 }
390
393}
394
395////////////////////////////////////////////////////////////////////////////////
396/// Return internet address of local host to which the socket is bound.
397/// In case of error TInetAddress::IsValid() returns kFALSE.
398
400{
401 if (IsValid()) {
402 if (fLocalAddress.GetPort() == -1)
404 return fLocalAddress;
405 }
406 return TInetAddress();
407}
408
409////////////////////////////////////////////////////////////////////////////////
410/// Return the local port # to which the socket is bound.
411/// In case of error return -1.
412
414{
415 if (IsValid()) {
416 if (fLocalAddress.GetPort() == -1)
418 return fLocalAddress.GetPort();
419 }
420 return -1;
421}
422
423////////////////////////////////////////////////////////////////////////////////
424/// Waits for this socket to change status. If interest=kRead,
425/// the socket will be watched to see if characters become available for
426/// reading; if interest=kWrite the socket will be watched to
427/// see if a write will not block.
428/// The argument 'timeout' specifies a maximum time to wait in millisec.
429/// Default no timeout.
430/// Returns 1 if a change of status of interest has been detected within
431/// timeout; 0 in case of timeout; < 0 if an error occurred.
432
434{
435 Int_t rc = 1;
436
437 // Associate a TFileHandler to this socket
439
440 // Wait for an event now
441 rc = gSystem->Select(&fh, timeout);
442
443 return rc;
444}
445
446////////////////////////////////////////////////////////////////////////////////
447/// Send a single message opcode. Use kind (opcode) to set the
448/// TMessage "what" field. Returns the number of bytes that were sent
449/// (always sizeof(Int_t)) and -1 in case of error. In case the kind has
450/// been or'ed with kMESS_ACK, the call will only return after having
451/// received an acknowledgement, making the sending process synchronous.
452
454{
456
457 Int_t nsent;
458 if ((nsent = Send(mess)) < 0)
459 return -1;
460
461 return nsent;
462}
463
464////////////////////////////////////////////////////////////////////////////////
465/// Send a status and a single message opcode. Use kind (opcode) to set the
466/// TMessage "what" field. Returns the number of bytes that were sent
467/// (always 2*sizeof(Int_t)) and -1 in case of error. In case the kind has
468/// been or'ed with kMESS_ACK, the call will only return after having
469/// received an acknowledgement, making the sending process synchronous.
470
472{
474 mess << status;
475
476 Int_t nsent;
477 if ((nsent = Send(mess)) < 0)
478 return -1;
479
480 return nsent;
481}
482
483////////////////////////////////////////////////////////////////////////////////
484/// Send a character string buffer. Use kind to set the TMessage "what" field.
485/// Returns the number of bytes in the string str that were sent and -1 in
486/// case of error. In case the kind has been or'ed with kMESS_ACK, the call
487/// will only return after having received an acknowledgement, making the
488/// sending process synchronous.
489
490Int_t TSocket::Send(const char *str, Int_t kind)
491{
493 if (str) mess.WriteString(str);
494
495 Int_t nsent;
496 if ((nsent = Send(mess)) < 0)
497 return -1;
498
499 return nsent - sizeof(Int_t); // - TMessage::What()
500}
501
502////////////////////////////////////////////////////////////////////////////////
503/// Send a TMessage object. Returns the number of bytes in the TMessage
504/// that were sent and -1 in case of error. In case the TMessage::What
505/// has been or'ed with kMESS_ACK, the call will only return after having
506/// received an acknowledgement, making the sending process synchronous.
507/// Returns -4 in case of kNoBlock and errno == EWOULDBLOCK.
508/// Returns -5 if pipe broken or reset by peer (EPIPE || ECONNRESET).
509/// support for streaming TStreamerInfo added by Rene Brun May 2008
510/// support for streaming TProcessID added by Rene Brun June 2008
511
513{
515
516 if (fSocket < 0) return -1;
517
518 if (mess.IsReading()) {
519 Error("Send", "cannot send a message used for reading");
520 return -1;
521 }
522
523 // send streamer infos in case schema evolution is enabled in the TMessage
525
526 // send the process id's so TRefs work
528
529 mess.SetLength(); //write length in first word of buffer
530
531 if (GetCompressionLevel() > 0 && mess.GetCompressionLevel() == 0)
533
534 if (mess.GetCompressionLevel() > 0)
535 const_cast<TMessage&>(mess).Compress();
536
537 char *mbuf = mess.Buffer();
538 Int_t mlen = mess.Length();
539 if (mess.CompBuffer()) {
540 mbuf = mess.CompBuffer();
541 mlen = mess.CompLength();
542 }
543
545 Int_t nsent;
546 if ((nsent = gSystem->SendRaw(fSocket, mbuf, mlen, 0)) <= 0) {
547 if (nsent == -5) {
548 // Connection reset by peer or broken
550 }
551 return nsent;
552 }
553
554 fBytesSent += nsent;
556
557 // If acknowledgement is desired, wait for it
558 if (mess.What() & kMESS_ACK) {
561 char buf[2];
562 Int_t n = 0;
563 if ((n = gSystem->RecvRaw(fSocket, buf, sizeof(buf), 0)) < 0) {
564 if (n == -5) {
565 // Connection reset by peer or broken
567 } else
568 n = -1;
569 return n;
570 }
571 if (strncmp(buf, "ok", 2)) {
572 Error("Send", "bad acknowledgement");
573 return -1;
574 }
575 fBytesRecv += 2;
576 fgBytesRecv += 2;
577 }
578
579 Touch(); // update usage timestamp
580
581 return nsent - sizeof(UInt_t); //length - length header
582}
583
584////////////////////////////////////////////////////////////////////////////////
585/// Send an object. Returns the number of bytes sent and -1 in case of error.
586/// In case the "kind" has been or'ed with kMESS_ACK, the call will only
587/// return after having received an acknowledgement, making the sending
588/// synchronous.
589
591{
592 //stream object to message buffer
594 mess.WriteObject(obj);
595
596 //now sending the object itself
597 Int_t nsent;
598 if ((nsent = Send(mess)) < 0)
599 return -1;
600
601 return nsent;
602}
603
604////////////////////////////////////////////////////////////////////////////////
605/// Send a raw buffer of specified length. Using option kOob one can send
606/// OOB data. Returns the number of bytes sent or -1 in case of error.
607/// Returns -4 in case of kNoBlock and errno == EWOULDBLOCK.
608/// Returns -5 if pipe broken or reset by peer (EPIPE || ECONNRESET).
609
611{
613
614 if (!IsValid()) return -1;
615
617 Int_t nsent;
618 if ((nsent = gSystem->SendRaw(fSocket, buffer, length, (int) opt)) <= 0) {
619 if (nsent == -5) {
620 // Connection reset or broken: close
622 }
623 return nsent;
624 }
625
626 fBytesSent += nsent;
628
629 Touch(); // update usage timestamp
630
631 return nsent;
632}
633
634////////////////////////////////////////////////////////////////////////////////
635/// Check if TStreamerInfo must be sent. The list of TStreamerInfo of classes
636/// in the object in the message is in the fInfos list of the message.
637/// We send only the TStreamerInfos not yet sent on this socket.
638
640{
641 if (mess.fInfos && mess.fInfos->GetEntries()) {
642 TIter next(mess.fInfos);
644 TList *minilist = 0;
645 while ((info = (TStreamerInfo*)next())) {
646 Int_t uid = info->GetNumber();
647 if (fBitsInfo.TestBitNumber(uid))
648 continue; //TStreamerInfo had already been sent
650 if (!minilist)
651 minilist = new TList();
652 if (gDebug > 0)
653 Info("SendStreamerInfos", "sending TStreamerInfo: %s, version = %d",
654 info->GetName(),info->GetClassVersion());
655 minilist->Add(info);
656 }
657 if (minilist) {
659 messinfo.WriteObject(minilist);
660 delete minilist;
661 if (messinfo.fInfos)
662 messinfo.fInfos->Clear();
663 if (Send(messinfo) < 0)
664 Warning("SendStreamerInfos", "problems sending TStreamerInfo's ...");
665 }
666 }
667}
668
669////////////////////////////////////////////////////////////////////////////////
670/// Check if TProcessIDs must be sent. The list of TProcessIDs
671/// in the object in the message is found by looking in the TMessage bits.
672/// We send only the TProcessIDs not yet send on this socket.
673
675{
676 if (mess.TestBitNumber(0)) {
678 Int_t npids = pids->GetEntries();
680 TList *minilist = 0;
681 for (Int_t ipid = 0; ipid < npids; ipid++) {
682 pid = (TProcessID*)pids->At(ipid);
683 if (!pid || !mess.TestBitNumber(pid->GetUniqueID()+1))
684 continue;
685 //check if a pid with this title has already been sent through the socket
686 //if not add it to the fUUIDs list
687 if (!fUUIDs) {
688 fUUIDs = new TList();
690 } else {
691 if (fUUIDs->FindObject(pid->GetTitle()))
692 continue;
693 }
694 fUUIDs->Add(new TObjString(pid->GetTitle()));
695 if (!minilist)
696 minilist = new TList();
697 if (gDebug > 0)
698 Info("SendProcessIDs", "sending TProcessID: %s", pid->GetTitle());
699 minilist->Add(pid);
700 }
701 if (minilist) {
703 messpid.WriteObject(minilist);
704 delete minilist;
705 if (Send(messpid) < 0)
706 Warning("SendProcessIDs", "problems sending TProcessID's ...");
707 }
708 }
709}
710
711////////////////////////////////////////////////////////////////////////////////
712/// Receive a character string message of maximum max length. The expected
713/// message must be of type kMESS_STRING. Returns length of received string
714/// (can be 0 if otherside of connection is closed) or -1 in case of error
715/// or -4 in case a non-blocking socket would block (i.e. there is nothing
716/// to be read).
717
718Int_t TSocket::Recv(char *str, Int_t max)
719{
720 Int_t n, kind;
721
723 if ((n = Recv(str, max, kind)) <= 0) {
724 if (n == -5) {
726 n = -1;
727 }
728 return n;
729 }
730
731 if (kind != kMESS_STRING) {
732 Error("Recv", "got message of wrong kind (expected %d, got %d)",
734 return -1;
735 }
736
737 return n;
738}
739
740////////////////////////////////////////////////////////////////////////////////
741/// Receive a character string message of maximum max length. Returns in
742/// kind the message type. Returns length of received string+4 (can be 0 if
743/// other side of connection is closed) or -1 in case of error or -4 in
744/// case a non-blocking socket would block (i.e. there is nothing to be read).
745
747{
748 Int_t n;
749 TMessage *mess;
750
752 if ((n = Recv(mess)) <= 0) {
753 if (n == -5) {
755 n = -1;
756 }
757 return n;
758 }
759
760 kind = mess->What();
761 if (str) {
762 if (mess->BufferSize() > (Int_t)sizeof(Int_t)) // if mess contains more than kind
763 mess->ReadString(str, max);
764 else
765 str[0] = 0;
766 }
767
768 delete mess;
769
770 return n; // number of bytes read (len of str + sizeof(kind)
771}
772
773////////////////////////////////////////////////////////////////////////////////
774/// Receives a status and a message type. Returns length of received
775/// integers, 2*sizeof(Int_t) (can be 0 if other side of connection
776/// is closed) or -1 in case of error or -4 in case a non-blocking
777/// socket would block (i.e. there is nothing to be read).
778
780{
781 Int_t n;
782 TMessage *mess;
783
785 if ((n = Recv(mess)) <= 0) {
786 if (n == -5) {
788 n = -1;
789 }
790 return n;
791 }
792
793 kind = mess->What();
794 (*mess) >> status;
795
796 delete mess;
797
798 return n; // number of bytes read (2 * sizeof(Int_t)
799}
800
801////////////////////////////////////////////////////////////////////////////////
802/// Receive a TMessage object. The user must delete the TMessage object.
803/// Returns length of message in bytes (can be 0 if other side of connection
804/// is closed) or -1 in case of error or -4 in case a non-blocking socket
805/// would block (i.e. there is nothing to be read) or -5 if pipe broken
806/// or reset by peer (EPIPE || ECONNRESET). In those case mess == nullptr.
807
809{
811
812 if (!IsValid()) {
813 mess = nullptr;
814 return -1;
815 }
816
817 Int_t n;
818 while (1) {
820 UInt_t len;
821 if ((n = gSystem->RecvRaw(fSocket, &len, sizeof(UInt_t), 0)) <= 0) {
822 if (n == 0 || n == -5) {
823 // Connection closed, reset or broken
825 }
826 mess = nullptr;
827 return n;
828 }
829 len = net2host(len); //from network to host byte order
830
831 if (len > (std::numeric_limits<decltype(len)>::max() - sizeof(decltype(len)))) {
832 Error("Recv", "Buffer length is %u and %u+sizeof(UInt_t) cannot be represented as an UInt_t.", len, len);
833 return -1;
834 }
835
837 char *buf = new char[len+sizeof(UInt_t)];
838 if ((n = gSystem->RecvRaw(fSocket, buf+sizeof(UInt_t), len, 0)) <= 0) {
839 if (n == 0 || n == -5) {
840 // Connection closed, reset or broken
842 }
843 delete [] buf;
844 mess = nullptr;
845 return n;
846 }
847
848 fBytesRecv += n + sizeof(UInt_t);
849 fgBytesRecv += n + sizeof(UInt_t);
850
851 // `buf` becomes owned by the TMessage.
852 mess = new TMessage(buf, len+sizeof(UInt_t));
853
854 // receive any streamer infos
857 // do another loop. No need to delete `mess` because RecvStreamerInfos already did it.
858 continue;
859 }
860
861 // receive any process ids
863 if (processIdReceived) {
864 // do another loop. No need to delete `mess` because RecvProcessIDs already did it.
865 continue;
866 }
867
868 break;
869 }
870
871 if (mess->What() & kMESS_ACK) {
873 const char ok[2] = { 'o', 'k' };
874 Int_t n2 = 0;
875 if ((n2 = gSystem->SendRaw(fSocket, ok, sizeof(ok), 0)) < 0) {
876 if (n2 == -5) {
877 // Connection reset or broken
879 }
880 delete mess;
881 mess = nullptr;
882 return n2;
883 }
884 mess->SetWhat(mess->What() & ~kMESS_ACK);
885
886 fBytesSent += 2;
887 fgBytesSent += 2;
888 }
889
890 Touch(); // update usage timestamp
891
892 return n;
893}
894
895////////////////////////////////////////////////////////////////////////////////
896/// Receive a raw buffer of specified length bytes. Using option kPeek
897/// one can peek at incoming data. Returns number of received bytes.
898/// Returns -1 in case of error. In case of opt == kOob: -2 means
899/// EWOULDBLOCK and -3 EINVAL. In case of non-blocking mode (kNoBlock)
900/// -4 means EWOULDBLOCK. Returns -5 if pipe broken or reset by
901/// peer (EPIPE || ECONNRESET).
902
904{
906
907 if (!IsValid()) return -1;
908 if (length == 0) return 0;
909
911 Int_t n;
912 if ((n = gSystem->RecvRaw(fSocket, buffer, length, (int) opt)) <= 0) {
913 if (n == 0 || n == -5) {
914 // Connection closed, reset or broken
916 }
917 return n;
918 }
919
920 fBytesRecv += n;
921 fgBytesRecv += n;
922
923 Touch(); // update usage timestamp
924
925 return n;
926}
927
928////////////////////////////////////////////////////////////////////////////////
929/// Receive a message containing streamer infos. In case the message contains
930/// streamer infos they are imported, the message will be deleted and the
931/// method returns kTRUE.
932
934{
935 if (mess->What() == kMESS_STREAMERINFO) {
936 TList *list = (TList*)mess->ReadObject(TList::Class());
937 TIter next(list);
939 TObjLink *lnk = list->FirstLink();
940 // First call BuildCheck for regular class
941 while (lnk) {
942 info = (TStreamerInfo*)lnk->GetObject();
943 TObject *element = info->GetElements()->UncheckedAt(0);
944 Bool_t isstl = element && strcmp("This",element->GetName())==0;
945 if (!isstl) {
946 info->BuildCheck();
947 if (gDebug > 0)
948 Info("RecvStreamerInfos", "importing TStreamerInfo: %s, version = %d",
949 info->GetName(), info->GetClassVersion());
950 }
951 lnk = lnk->Next();
952 }
953 // Then call BuildCheck for stl class
954 lnk = list->FirstLink();
955 while (lnk) {
956 info = (TStreamerInfo*)lnk->GetObject();
957 TObject *element = info->GetElements()->UncheckedAt(0);
958 Bool_t isstl = element && strcmp("This",element->GetName())==0;
959 if (isstl) {
960 info->BuildCheck();
961 if (gDebug > 0)
962 Info("RecvStreamerInfos", "importing TStreamerInfo: %s, version = %d",
963 info->GetName(), info->GetClassVersion());
964 }
965 lnk = lnk->Next();
966 }
967 delete list;
968 delete mess;
969
970 return kTRUE;
971 }
972 return kFALSE;
973}
974
975////////////////////////////////////////////////////////////////////////////////
976/// Receive a message containing process ids. In case the message contains
977/// process ids they are imported, the message will be deleted and the
978/// method returns kTRUE.
979
981{
982 if (mess->What() == kMESS_PROCESSID) {
983 TList *list = (TList*)mess->ReadObject(TList::Class());
984 TIter next(list);
986 while ((pid = (TProcessID*)next())) {
987 // check that a similar pid is not already registered in fgPIDs
990 TProcessID *p;
991 while ((p = (TProcessID*)nextpid())) {
992 if (!strcmp(p->GetTitle(), pid->GetTitle())) {
993 delete pid;
994 pid = 0;
995 break;
996 }
997 }
998 if (pid) {
999 if (gDebug > 0)
1000 Info("RecvProcessIDs", "importing TProcessID: %s", pid->GetTitle());
1001 pid->IncrementCount();
1002 pidslist->Add(pid);
1003 Int_t ind = pidslist->IndexOf(pid);
1004 pid->SetUniqueID((UInt_t)ind);
1005 }
1006 }
1007 delete list;
1008 delete mess;
1009
1010 return kTRUE;
1011 }
1012 return kFALSE;
1013}
1014
1015////////////////////////////////////////////////////////////////////////////////
1016/// Set socket options.
1017
1019{
1020 if (!IsValid()) return -1;
1021
1022 return gSystem->SetSockOpt(fSocket, opt, val);
1023}
1024
1025////////////////////////////////////////////////////////////////////////////////
1026/// Get socket options. Returns -1 in case of error.
1027
1029{
1030 if (!IsValid()) return -1;
1031
1032 return gSystem->GetSockOpt(fSocket, opt, &val);
1033}
1034
1035////////////////////////////////////////////////////////////////////////////////
1036/// Returns error code. Meaning depends on context where it is called.
1037/// If no error condition returns 0 else a value < 0.
1038/// For example see TServerSocket ctor.
1039
1041{
1042 if (!IsValid())
1043 return fSocket;
1044
1045 return 0;
1046}
1047
1048////////////////////////////////////////////////////////////////////////////////
1049/// See comments for function SetCompressionSettings
1050
1061
1062////////////////////////////////////////////////////////////////////////////////
1063/// See comments for function SetCompressionSettings
1064
1066{
1067 if (level < 0) level = 0;
1068 if (level > 99) level = 99;
1069 if (fCompress < 0) {
1070 // if the algorithm is not defined yet use 0 as a default
1071 fCompress = level;
1072 } else {
1073 int algorithm = fCompress / 100;
1075 fCompress = 100 * algorithm + level;
1076 }
1077}
1078
1079////////////////////////////////////////////////////////////////////////////////
1080/// Used to specify the compression level and algorithm:
1081/// settings = 100 * algorithm + level
1082///
1083/// level = 0, objects written to this file will not be compressed.
1084/// level = 1, minimal compression level but fast.
1085/// ....
1086/// level = 9, maximal compression level but slower and might use more memory.
1087/// (For the currently supported algorithms, the maximum level is 9)
1088/// If compress is negative it indicates the compression level is not set yet.
1089///
1090/// The enumeration ROOT::RCompressionSetting::EAlgorithm associates each
1091/// algorithm with a number. There is a utility function to help
1092/// to set the value of the argument. For example,
1093/// ROOT::CompressionSettings(ROOT::kLZMA, 1)
1094/// will build an integer which will set the compression to use
1095/// the LZMA algorithm and compression level 1. These are defined
1096/// in the header file Compression.h.
1097///
1098/// Note that the compression settings may be changed at any time.
1099/// The new compression settings will only apply to branches created
1100/// or attached after the setting is changed and other objects written
1101/// after the setting is changed.
1102
1107
1108////////////////////////////////////////////////////////////////////////////////
1109/// Static method returning supported client protocol.
1110
1115
1116////////////////////////////////////////////////////////////////////////////////
1117/// Print error string depending on error code.
1118
1120{
1121 // Make sure it is in range
1122 err = (err < kErrError) ? ((err > -1) ? err : 0) : kErrError;
1123
1124 if (gDebug > 0)
1125 ::Error(where, "%s", gRootdErrStr[err]);
1126}
1127
1128////////////////////////////////////////////////////////////////////////////////
1129/// Get total number of bytes sent via all sockets.
1130
1135
1136////////////////////////////////////////////////////////////////////////////////
1137/// Get total number of bytes received via all sockets.
1138
UShort_t net2host(UShort_t x)
Definition Bytes.h:561
@ kMESS_STRING
@ kMESS_ACK
@ kMESS_PROCESSID
@ kMESS_STREAMERINFO
R__EXTERN const char * gRootdErrStr[]
Definition NetErrors.h:76
@ kErrError
Definition NetErrors.h:73
#define SafeDelete(p)
Definition RConfig.hxx:507
char * host
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
long Long_t
Signed long integer 4 bytes (long). Size depends on architecture.
Definition RtypesCore.h:69
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
Definition RtypesCore.h:61
constexpr Bool_t kFALSE
Definition RtypesCore.h:109
unsigned long long ULong64_t
Portable unsigned long integer 8 bytes.
Definition RtypesCore.h:85
constexpr Bool_t kTRUE
Definition RtypesCore.h:108
const char Option_t
Option string (const char)
Definition RtypesCore.h:81
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:130
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t option
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h length
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
Definition TROOT.cxx:792
#define gROOT
Definition TROOT.h:417
ESockOptions
Definition TSystem.h:229
ESendRecvOptions
Definition TSystem.h:242
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
Bool_t TestBitNumber(UInt_t bitnumber) const
Definition TBits.h:222
void SetBitNumber(UInt_t bitnumber, Bool_t value=kTRUE)
Definition TBits.h:206
virtual void SetOwner(Bool_t enable=kTRUE)
Set whether this collection is the owner (enable==true) of its content.
This class represents an Internet Protocol (IP) address.
Int_t GetPort() const
const char * GetHostName() const
A doubly linked list.
Definition TList.h:38
static TClass * Class()
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:708
void Add(TObject *obj) override
Definition TList.h:81
Int_t Compress()
Compress the message.
Definition TMessage.cxx:318
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition TNamed.cxx:173
TString fName
Definition TNamed.h:32
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition TNamed.cxx:149
An array of TObjects.
Definition TObjArray.h:31
Collectable string class.
Definition TObjString.h:28
Mother of all ROOT objects.
Definition TObject.h:42
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1082
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:886
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1096
void ResetBit(UInt_t f)
Definition TObject.h:203
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1070
A TProcessID identifies a ROOT job in a unique way in time and space.
Definition TProcessID.h:74
static TObjArray * GetPIDs()
static: returns array of TProcessIDs
This class implements client sockets.
Definition TSocket.h:39
TInetAddress fAddress
Definition TSocket.h:63
Int_t fCompress
Definition TSocket.h:66
virtual Int_t SetOption(ESockOptions opt, Int_t val)
Set socket options.
Definition TSocket.cxx:1018
Int_t fSocket
Definition TSocket.h:71
Int_t GetErrorCode() const
Returns error code.
Definition TSocket.cxx:1040
TVirtualMutex * fLastUsageMtx
Definition TSocket.h:77
void SetCompressionLevel(Int_t level=ROOT::RCompressionSetting::ELevel::kUseMin)
See comments for function SetCompressionSettings.
Definition TSocket.cxx:1065
void SendStreamerInfos(const TMessage &mess)
Check if TStreamerInfo must be sent.
Definition TSocket.cxx:639
@ kInvalidStillInList
Definition TSocket.h:61
@ kInvalid
Definition TSocket.h:57
TString fUrl
Definition TSocket.h:73
void SetCompressionAlgorithm(Int_t algorithm=ROOT::RCompressionSetting::EAlgorithm::kUseGlobal)
See comments for function SetCompressionSettings.
Definition TSocket.cxx:1051
TSocket()
Definition TSocket.h:85
static ULong64_t GetSocketBytesSent()
Get total number of bytes sent via all sockets.
Definition TSocket.cxx:1131
TString fService
Definition TSocket.h:69
Bool_t RecvStreamerInfos(TMessage *mess)
Receive a message containing streamer infos.
Definition TSocket.cxx:933
virtual Int_t Recv(TMessage *&mess)
Receive a TMessage object.
Definition TSocket.cxx:808
TList * fUUIDs
Definition TSocket.h:75
static Int_t GetClientProtocol()
Static method returning supported client protocol.
Definition TSocket.cxx:1111
TBits fBitsInfo
Definition TSocket.h:74
TInetAddress fLocalAddress
Definition TSocket.h:67
static ULong64_t fgBytesRecv
Definition TSocket.h:80
@ kBrokenConn
Definition TSocket.h:45
virtual void Close(Option_t *opt="")
Close the socket.
Definition TSocket.cxx:379
void MarkBrokenConnection()
Close the socket and mark as due to a broken connection.
Definition TSocket.cxx:361
void Touch()
Definition TSocket.h:155
Bool_t RecvProcessIDs(TMessage *mess)
Receive a message containing process ids.
Definition TSocket.cxx:980
Int_t GetCompressionLevel() const
Definition TSocket.h:174
virtual Int_t RecvRaw(void *buffer, Int_t length, ESendRecvOptions opt=kDefault)
Receive a raw buffer of specified length bytes.
Definition TSocket.cxx:903
static ULong64_t fgBytesSent
Definition TSocket.h:81
virtual Int_t SendRaw(const void *buffer, Int_t length, ESendRecvOptions opt=kDefault)
Send a raw buffer of specified length.
Definition TSocket.cxx:610
void SendProcessIDs(const TMessage &mess)
Check if TProcessIDs must be sent.
Definition TSocket.cxx:674
static Int_t fgClientProtocol
Definition TSocket.h:83
virtual TInetAddress GetLocalInetAddress()
Return internet address of local host to which the socket is bound.
Definition TSocket.cxx:399
virtual Int_t Select(Int_t interest=kRead, Long_t timeout=-1)
Waits for this socket to change status.
Definition TSocket.cxx:433
virtual Int_t GetLocalPort()
Return the local port # to which the socket is bound.
Definition TSocket.cxx:413
Int_t fTcpWindowSize
Definition TSocket.h:72
Option_t * GetOption() const override
Definition TSocket.h:99
@ kSOCKD
Definition TSocket.h:48
@ kROOTD
Definition TSocket.h:48
static void NetError(const char *where, Int_t error)
Print error string depending on error code.
Definition TSocket.cxx:1119
EServiceType fServType
Definition TSocket.h:70
virtual Int_t SendObject(const TObject *obj, Int_t kind=kMESS_OBJECT)
Send an object.
Definition TSocket.cxx:590
void SetCompressionSettings(Int_t settings=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault)
Used to specify the compression level and algorithm: settings = 100 * algorithm + level.
Definition TSocket.cxx:1103
UInt_t fBytesSent
Definition TSocket.h:65
Int_t fRemoteProtocol
Definition TSocket.h:68
UInt_t fBytesRecv
Definition TSocket.h:64
virtual Bool_t IsValid() const
Definition TSocket.h:131
virtual Int_t Send(const TMessage &mess)
Send a TMessage object.
Definition TSocket.cxx:512
static ULong64_t GetSocketBytesRecv()
Get total number of bytes received via all sockets.
Definition TSocket.cxx:1139
Describes a persistent version of a class.
Basic string class.
Definition TString.h:137
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2438
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:642
virtual int GetServiceByName(const char *service)
Get port # of internet service.
Definition TSystem.cxx:2339
virtual TInetAddress GetSockName(int sock)
Get Internet Protocol (IP) address of host and port #.
Definition TSystem.cxx:2330
static void ResetErrno()
Static function resetting system error number.
Definition TSystem.cxx:287
virtual char * GetServiceByPort(int port)
Get name of internet service.
Definition TSystem.cxx:2348
virtual int SetSockOpt(int sock, int kind, int val)
Set socket option.
Definition TSystem.cxx:2457
virtual TInetAddress GetPeerName(int sock)
Get Internet Protocol (IP) address of remote host and port #.
Definition TSystem.cxx:2321
virtual int OpenConnection(const char *server, int port, int tcpwindowsize=-1, const char *protocol="tcp")
Open a connection to another host.
Definition TSystem.cxx:2357
virtual int GetSockOpt(int sock, int kind, int *val)
Get socket option.
Definition TSystem.cxx:2466
virtual int RecvRaw(int sock, void *buffer, int length, int flag)
Receive exactly length bytes into buffer.
Definition TSystem.cxx:2420
virtual Int_t Select(TList *active, Long_t timeout)
Select on active file descriptors (called by TMonitor).
Definition TSystem.cxx:448
virtual TInetAddress GetHostByName(const char *server)
Get Internet Protocol (IP) address of host.
Definition TSystem.cxx:2312
virtual int SendRaw(int sock, const void *buffer, int length, int flag)
Send exactly length bytes from buffer.
Definition TSystem.cxx:2430
virtual void CloseConnection(int sock, Bool_t force=kFALSE)
Close socket connection.
Definition TSystem.cxx:2411
This class represents a WWW compatible URL.
Definition TUrl.h:33
const Int_t n
Definition legend1.C:16
@ kUndefined
Undefined compression algorithm (must be kept the last of the list in case a new algorithm is added).
@ kUseMin
Compression level reserved when we are not sure what to use (1 is for the fastest compression)
Definition Compression.h:72