Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TServerSocket.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 TServerSocket.cxx
14\class TServerSocket
15\brief This class implements server 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
19This class implements server sockets. A server socket waits for
20requests to come in over the network. It performs some operation
21based on that request and then possibly returns a full duplex socket
22to the requester. The actual work is done via the TSystem class
23(either TUnixSystem or TWinNTSystem).
24
25**/
26
27
28#include "TServerSocket.h"
29#include "TSocket.h"
30#include "TSystem.h"
31#include "TROOT.h"
32#include "TError.h"
33#include <string>
34#include "TVirtualMutex.h"
35
36// Hook to server authentication wrapper
39
40// Defaul options for accept
42
44
45
46////////////////////////////////////////////////////////////////////////////////
47/// Kind of macro to parse input options
48/// Modify opt according to modifier mod.
49
50static void SetAuthOpt(UChar_t &opt, UChar_t mod)
51{
53
54 if (!mod) return;
55
57 if ((mod & ROOT::Deprecated::kSrvNoAuth)) opt &= ~ROOT::Deprecated::kSrvAuth;
58}
59
60////////////////////////////////////////////////////////////////////////////////
61/// Create a server socket object for a named service. Set reuse to true
62/// to force reuse of the server socket (i.e. do not wait for the time
63/// out to pass). Using backlog one can set the desirable queue length
64/// for pending connections.
65/// Use tcpwindowsize to specify the size of the receive buffer, it has
66/// to be specified here to make sure the window scale option is set (for
67/// tcpwindowsize > 65KB and for platforms supporting window scaling).
68/// The socketBindOption parameter allows to specify how the socket will be
69/// bound. See the documentation of ESocketBindOption for the details.
70/// Use IsValid() to check the validity of the
71/// server socket. In case server socket is not valid use GetErrorCode()
72/// to obtain the specific error value. These values are:
73/// 0 = no error (socket is valid)
74/// -1 = low level socket() call failed
75/// -2 = low level bind() call failed
76/// -3 = low level listen() call failed
77/// Every valid server socket is added to the TROOT sockets list which
78/// will make sure that any open sockets are properly closed on
79/// program termination.
80
83{
86
87 SetName("ServerSocket");
88
89 fSecContext = 0;
90 fSecContexts = new TList;
91
92 // If this is a local path, try announcing a UNIX socket service
96 service[0] == '/')) {
97#else
98 service[0] == '/' || (service[1] == ':' && service[2] == '/'))) {
99#endif
101 fService = "unix:";
102 fService += service;
104 if (fSocket >= 0) {
106 gROOT->GetListOfSockets()->Add(this);
107 }
108 } else {
109 // TCP / UDP socket
111 int port = gSystem->GetServiceByName(service);
112 if (port != -1) {
114 if (fSocket >= 0) {
116 gROOT->GetListOfSockets()->Add(this);
117 }
118 } else {
119 fSocket = -1;
120 }
121 }
122}
123
124////////////////////////////////////////////////////////////////////////////////
125/// Create a server socket object on a specified port. Set reuse to true
126/// to force reuse of the server socket (i.e. do not wait for the time
127/// out to pass). Using backlog one can set the desirable queue length
128/// for pending connections. If port is 0 a port scan will be done to
129/// find a free port. This option is mutual exlusive with the reuse option.
130/// Use tcpwindowsize to specify the size of the receive buffer, it has
131/// to be specified here to make sure the window scale option is set (for
132/// tcpwindowsize > 65KB and for platforms supporting window scaling).
133/// The socketBindOption parameter allows to specify how the socket will be
134/// bound. See the documentation of ESocketBindOption for the details.
135/// Use IsValid() to check the validity of the
136/// server socket. In case server socket is not valid use GetErrorCode()
137/// to obtain the specific error value. These values are:
138/// 0 = no error (socket is valid)
139/// -1 = low level socket() call failed
140/// -2 = low level bind() call failed
141/// -3 = low level listen() call failed
142/// Every valid server socket is added to the TROOT sockets list which
143/// will make sure that any open sockets are properly closed on
144/// program termination.
145
148{
151
152 SetName("ServerSocket");
153
154 fSecContext = 0;
155 fSecContexts = new TList;
158
160 if (fSocket >= 0) {
162 gROOT->GetListOfSockets()->Add(this);
163 }
164}
165
166////////////////////////////////////////////////////////////////////////////////
167/// Destructor: cleanup authentication stuff (if any) and close
168
170{
172 if (fSecContexts) {
173 if (fgSrvAuthClupHook) {
174 // Cleanup the security contexts
175 (*fgSrvAuthClupHook)(fSecContexts);
176 }
177 // Remove the list
180 fSecContexts = 0;
181 }
182
183 Close();
184}
185
186////////////////////////////////////////////////////////////////////////////////
187/// Accept a connection on a server socket. Returns a full-duplex
188/// communication TSocket object. If no pending connections are
189/// present on the queue and nonblocking mode has not been enabled
190/// with SetOption(kNoBlock,1) the call blocks until a connection is
191/// present. The returned socket must be deleted by the user. The socket
192/// is also added to the TROOT sockets list which will make sure that
193/// any open sockets are properly closed on program termination.
194/// In case of error 0 is returned and in case non-blocking I/O is
195/// enabled and no connections are available -1 is returned.
196
198{
199 if (fSocket == -1) { return 0; }
200
201 TSocket *socket = new TSocket;
202
204 if (soc == -1) { delete socket; return 0; }
205 if (soc == -2) { delete socket; return (TSocket*) -1; }
206
207 // Parse Opt
209 SetAuthOpt(acceptOpt, opt);
211
212 socket->fSocket = soc;
213 socket->fSecContext = 0;
214 socket->fService = fService;
216 socket->fAddress = gSystem->GetPeerName(socket->fSocket);
217 if (socket->fSocket >= 0) {
219 gROOT->GetListOfSockets()->Add(socket);
220 }
221
222 // Perform authentication, if required
223 if (auth) {
224 if (!Authenticate(socket)) {
225 delete socket;
226 socket = 0;
227 }
228 }
229
230 return socket;
231}
232
233////////////////////////////////////////////////////////////////////////////////
234/// Return internet address of host to which the server socket is bound,
235/// i.e. the local host. In case of error TInetAddress::IsValid() returns
236/// kFALSE.
237
239{
240 if (fSocket != -1) {
241 if (fAddress.GetPort() == -1)
243 return fAddress;
244 }
245 return TInetAddress();
246}
247
248////////////////////////////////////////////////////////////////////////////////
249/// Get port # to which server socket is bound. In case of error returns -1.
250
252{
253 if (fSocket != -1) {
254 if (fAddress.GetPort() == -1)
256 return fAddress.GetPort();
257 }
258 return -1;
259}
260
261
262////////////////////////////////////////////////////////////////////////////////
263/// Return default options for Accept
264
269
270////////////////////////////////////////////////////////////////////////////////
271/// Set default options for Accept according to modifier 'mod'.
272/// Use:
273/// kSrvAuth require client authentication
274/// kSrvNoAuth do not require client authentication
275
280
281////////////////////////////////////////////////////////////////////////////////
282/// Print default options for Accept.
283
285{
286 ::Info("ShowAcceptOptions", "Use authentication: %s", (fgAcceptOpt & ROOT::Deprecated::kSrvAuth) ? "yes" : "no");
287}
288
289////////////////////////////////////////////////////////////////////////////////
290/// Check authentication request from the client on new
291/// open connection
292
294{
295 if (!fgSrvAuthHook) {
297
298 // Load libraries needed for (server) authentication ...
299 TString srvlib = "libSrvAuth";
300 char *p = 0;
301 // The generic one
302 if ((p = gSystem->DynamicPathName(srvlib, kTRUE))) {
303 delete[] p;
304 if (gSystem->Load(srvlib) == -1) {
305 Error("Authenticate", "can't load %s",srvlib.Data());
306 return kFALSE;
307 }
308 } else {
309 Error("Authenticate", "can't locate %s",srvlib.Data());
310 return kFALSE;
311 }
312 //
313 // Locate SrvAuthenticate
314 Func_t f = gSystem->DynFindSymbol(srvlib,"SrvAuthenticate");
315 if (f)
317 else {
318 Error("Authenticate", "can't find SrvAuthenticate");
319 return kFALSE;
320 }
321 //
322 // Locate SrvAuthCleanup
323 f = gSystem->DynFindSymbol(srvlib,"SrvAuthCleanup");
324 if (f)
326 else {
327 Warning("Authenticate", "can't find SrvAuthCleanup");
328 }
329 }
330
332 if (!confdir.Length()) {
333 Error("Authenticate", "config dir undefined");
334 return kFALSE;
335 }
336
337 // dir for temporary files
340 tmpdir = TString("/tmp");
341
342 // Get Host name
344 if (gDebug > 2)
345 Info("Authenticate","OpenHost = %s", openhost.Data());
346
347 // Run Authentication now
348 std::string user;
349 Int_t meth = -1;
350 Int_t auth = 0;
351 Int_t type = 0;
352 std::string ctkn = "";
353 if (fgSrvAuthHook)
354 auth = (*fgSrvAuthHook)(sock, confdir, tmpdir, user,
356
357 if (gDebug > 2)
358 Info("Authenticate","auth = %d, type= %d, ctkn= %s",
359 auth, type, ctkn.c_str());
360
361 return auth;
362}
#define SafeDelete(p)
Definition RConfig.hxx:531
#define f(i)
Definition RSha256.hxx:104
bool Bool_t
Boolean (0=false, 1=true) (bool)
Definition RtypesCore.h:77
unsigned char UChar_t
Unsigned Character 1 byte (unsigned char)
Definition RtypesCore.h:52
constexpr Bool_t kFALSE
Definition RtypesCore.h:108
constexpr Bool_t kTRUE
Definition RtypesCore.h:107
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:125
winID h TVirtualViewer3D TVirtualGLPainter p
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 type
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:783
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:426
static void SetAuthOpt(UChar_t &opt, UChar_t mod)
Kind of macro to parse input options Modify opt according to modifier mod.
TVirtualMutex * gSrvAuthenticateMutex
void(* Func_t)()
Definition TSystem.h:249
@ kWritePermission
Definition TSystem.h:54
ESocketBindOption
Options for binging the sockets created.
Definition TSystem.h:46
@ kInaddrLoopback
Refers to the local host via the loopback device.
Definition TSystem.h:48
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
#define R__LOCKGUARD2(mutex)
#define R__LOCKGUARD(mutex)
void Delete(Option_t *option="") override=0
Delete this object.
This class represents an Internet Protocol (IP) address.
Int_t GetPort() const
const char * GetHostName() const
A doubly linked list.
Definition TList.h:38
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition TNamed.cxx:173
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition TNamed.cxx:149
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:204
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1081
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:885
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1095
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:1069
static const TString & GetRootSys()
Get the rootsys directory in the installation. Static utility function.
Definition TROOT.cxx:3149
static UChar_t GetAcceptOptions() R__DEPRECATED(6
Return default options for Accept.
static void SetAcceptOptions(UChar_t Opt) R__DEPRECATED(6
Set default options for Accept according to modifier 'mod'.
static UChar_t fgAcceptOpt
Bool_t Authenticate(TSocket *)
Check authentication request from the client on new open connection.
Int_t GetLocalPort() override
Get port # to which server socket is bound. In case of error returns -1.
virtual ~TServerSocket()
Destructor: cleanup authentication stuff (if any) and close.
virtual TSocket * Accept(UChar_t Opt=0)
Accept a connection on a server socket.
static ROOT::Deprecated::SrvAuth_t fgSrvAuthHook
TInetAddress GetLocalInetAddress() override
Return internet address of host to which the server socket is bound, i.e.
TSeqCollection * fSecContexts
static ROOT::Deprecated::SrvClup_t fgSrvAuthClupHook
static void ShowAcceptOptions() R__DEPRECATED(6
Print default options for Accept.
This class implements client sockets.
Definition TSocket.h:54
TInetAddress fAddress
Definition TSocket.h:79
Int_t fSocket
Definition TSocket.h:89
ROOT::Deprecated::TSecContext * fSecContext
Definition TSocket.h:85
TSocket()
Definition TSocket.h:103
TString fService
Definition TSocket.h:87
@ kIsUnix
Definition TSocket.h:60
virtual void Close(Option_t *opt="")
Close the socket.
Definition TSocket.cxx:398
TInetAddress GetInetAddress() const
Definition TSocket.h:133
Basic string class.
Definition TString.h:138
virtual int GetServiceByName(const char *service)
Get port # of internet service.
Definition TSystem.cxx:2329
virtual TInetAddress GetSockName(int sock)
Get Internet Protocol (IP) address of host and port #.
Definition TSystem.cxx:2320
virtual Func_t DynFindSymbol(const char *module, const char *entry)
Find specific entry point in specified library.
Definition TSystem.cxx:2055
virtual char * GetServiceByPort(int port)
Get name of internet service.
Definition TSystem.cxx:2338
virtual int AcceptConnection(int sock)
Accept a connection.
Definition TSystem.cxx:2392
virtual TInetAddress GetPeerName(int sock)
Get Internet Protocol (IP) address of remote host and port #.
Definition TSystem.cxx:2311
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1868
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1307
virtual int AnnounceUnixService(int port, int backlog)
Announce unix domain service.
Definition TSystem.cxx:2374
virtual int AnnounceTcpService(int port, Bool_t reuse, int backlog, int tcpwindowsize=-1, ESocketBindOption socketBindOption=ESocketBindOption::kInaddrAny)
Announce TCP/IP service.
Definition TSystem.cxx:2356
virtual const char * TempDirectory() const
Return a user configured or systemwide directory to create temporary files in.
Definition TSystem.cxx:1493
char * DynamicPathName(const char *lib, Bool_t quiet=kFALSE)
Find a dynamic library called lib using the system search paths.
Definition TSystem.cxx:2031
This class implements a mutex interface.
Int_t(* SrvAuth_t)(TSocket *sock, const char *, const char *, std::string &, Int_t &, Int_t &, std::string &, TSeqCollection *)
const UChar_t kSrvAuth
Int_t(* SrvClup_t)(TSeqCollection *)
const UChar_t kSrvNoAuth