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
46
47////////////////////////////////////////////////////////////////////////////////
48/// Kind of macro to parse input options
49/// Modify opt according to modifier mod.
50
51static void SetAuthOpt(UChar_t &opt, UChar_t mod)
52{
54
55 if (!mod) return;
56
57 if ((mod & kSrvAuth)) opt |= kSrvAuth;
58 if ((mod & kSrvNoAuth)) opt &= ~kSrvAuth;
59}
60
61////////////////////////////////////////////////////////////////////////////////
62/// Create a server socket object for a named service. Set reuse to true
63/// to force reuse of the server socket (i.e. do not wait for the time
64/// out to pass). Using backlog one can set the desirable queue length
65/// for pending connections.
66/// Use tcpwindowsize to specify the size of the receive buffer, it has
67/// to be specified here to make sure the window scale option is set (for
68/// tcpwindowsize > 65KB and for platforms supporting window scaling).
69/// The socketBindOption parameter allows to specify how the socket will be
70/// bound. See the documentation of ESocketBindOption for the details.
71/// Use IsValid() to check the validity of the
72/// server socket. In case server socket is not valid use GetErrorCode()
73/// to obtain the specific error value. These values are:
74/// 0 = no error (socket is valid)
75/// -1 = low level socket() call failed
76/// -2 = low level bind() call failed
77/// -3 = low level listen() call failed
78/// Every valid server socket is added to the TROOT sockets list which
79/// will make sure that any open sockets are properly closed on
80/// program termination.
81
84{
87
88 SetName("ServerSocket");
89
90 fSecContext = 0;
91 fSecContexts = new TList;
92
93 // If this is a local path, try announcing a UNIX socket service
97 service[0] == '/')) {
98#else
99 service[0] == '/' || (service[1] == ':' && service[2] == '/'))) {
100#endif
102 fService = "unix:";
103 fService += service;
105 if (fSocket >= 0) {
107 gROOT->GetListOfSockets()->Add(this);
108 }
109 } else {
110 // TCP / UDP socket
112 int port = gSystem->GetServiceByName(service);
113 if (port != -1) {
115 if (fSocket >= 0) {
117 gROOT->GetListOfSockets()->Add(this);
118 }
119 } else {
120 fSocket = -1;
121 }
122 }
123}
124
125////////////////////////////////////////////////////////////////////////////////
126/// Create a server socket object on a specified port. Set reuse to true
127/// to force reuse of the server socket (i.e. do not wait for the time
128/// out to pass). Using backlog one can set the desirable queue length
129/// for pending connections. If port is 0 a port scan will be done to
130/// find a free port. This option is mutual exlusive with the reuse option.
131/// Use tcpwindowsize to specify the size of the receive buffer, it has
132/// to be specified here to make sure the window scale option is set (for
133/// tcpwindowsize > 65KB and for platforms supporting window scaling).
134/// The socketBindOption parameter allows to specify how the socket will be
135/// bound. See the documentation of ESocketBindOption for the details.
136/// Use IsValid() to check the validity of the
137/// server socket. In case server socket is not valid use GetErrorCode()
138/// to obtain the specific error value. These values are:
139/// 0 = no error (socket is valid)
140/// -1 = low level socket() call failed
141/// -2 = low level bind() call failed
142/// -3 = low level listen() call failed
143/// Every valid server socket is added to the TROOT sockets list which
144/// will make sure that any open sockets are properly closed on
145/// program termination.
146
149{
152
153 SetName("ServerSocket");
154
155 fSecContext = 0;
156 fSecContexts = new TList;
159
161 if (fSocket >= 0) {
163 gROOT->GetListOfSockets()->Add(this);
164 }
165}
166
167////////////////////////////////////////////////////////////////////////////////
168/// Destructor: cleanup authentication stuff (if any) and close
169
171{
173 if (fSecContexts) {
174 if (fgSrvAuthClupHook) {
175 // Cleanup the security contexts
176 (*fgSrvAuthClupHook)(fSecContexts);
177 }
178 // Remove the list
181 fSecContexts = 0;
182 }
183
184 Close();
185}
186
187////////////////////////////////////////////////////////////////////////////////
188/// Accept a connection on a server socket. Returns a full-duplex
189/// communication TSocket object. If no pending connections are
190/// present on the queue and nonblocking mode has not been enabled
191/// with SetOption(kNoBlock,1) the call blocks until a connection is
192/// present. The returned socket must be deleted by the user. The socket
193/// is also added to the TROOT sockets list which will make sure that
194/// any open sockets are properly closed on program termination.
195/// In case of error 0 is returned and in case non-blocking I/O is
196/// enabled and no connections are available -1 is returned.
197///
198/// The opt can be used to require client authentication; valid options are
199///
200/// kSrvAuth = require client authentication
201/// kSrvNoAuth = force no client authentication
202///
203/// Example: use Opt = kSrvAuth to require client authentication.
204///
205/// Default options are taken from fgAcceptOpt and are initially
206/// equivalent to kSrvNoAuth; they can be changed with the static
207/// method TServerSocket::SetAcceptOptions(Opt).
208/// The active defaults can be visualized using the static method
209/// TServerSocket::ShowAcceptOptions().
210///
211
213{
214 if (fSocket == -1) { return 0; }
215
216 TSocket *socket = new TSocket;
217
219 if (soc == -1) { delete socket; return 0; }
220 if (soc == -2) { delete socket; return (TSocket*) -1; }
221
222 // Parse Opt
224 SetAuthOpt(acceptOpt, opt);
226
227 socket->fSocket = soc;
228 socket->fSecContext = 0;
229 socket->fService = fService;
231 socket->fAddress = gSystem->GetPeerName(socket->fSocket);
232 if (socket->fSocket >= 0) {
234 gROOT->GetListOfSockets()->Add(socket);
235 }
236
237 // Perform authentication, if required
238 if (auth) {
239 if (!Authenticate(socket)) {
240 delete socket;
241 socket = 0;
242 }
243 }
244
245 return socket;
246}
247
248////////////////////////////////////////////////////////////////////////////////
249/// Return internet address of host to which the server socket is bound,
250/// i.e. the local host. In case of error TInetAddress::IsValid() returns
251/// kFALSE.
252
254{
255 if (fSocket != -1) {
256 if (fAddress.GetPort() == -1)
258 return fAddress;
259 }
260 return TInetAddress();
261}
262
263////////////////////////////////////////////////////////////////////////////////
264/// Get port # to which server socket is bound. In case of error returns -1.
265
267{
268 if (fSocket != -1) {
269 if (fAddress.GetPort() == -1)
271 return fAddress.GetPort();
272 }
273 return -1;
274}
275
276
277////////////////////////////////////////////////////////////////////////////////
278/// Return default options for Accept
279
284
285////////////////////////////////////////////////////////////////////////////////
286/// Set default options for Accept according to modifier 'mod'.
287/// Use:
288/// kSrvAuth require client authentication
289/// kSrvNoAuth do not require client authentication
290
295
296////////////////////////////////////////////////////////////////////////////////
297/// Print default options for Accept.
298
300{
301 ::Info("ShowAcceptOptions", "Use authentication: %s", (fgAcceptOpt & kSrvAuth) ? "yes" : "no");
302}
303
304////////////////////////////////////////////////////////////////////////////////
305/// Check authentication request from the client on new
306/// open connection
307
309{
310 if (!fgSrvAuthHook) {
312
313 // Load libraries needed for (server) authentication ...
314 TString srvlib = "libSrvAuth";
315 char *p = 0;
316 // The generic one
317 if ((p = gSystem->DynamicPathName(srvlib, kTRUE))) {
318 delete[] p;
319 if (gSystem->Load(srvlib) == -1) {
320 Error("Authenticate", "can't load %s",srvlib.Data());
321 return kFALSE;
322 }
323 } else {
324 Error("Authenticate", "can't locate %s",srvlib.Data());
325 return kFALSE;
326 }
327 //
328 // Locate SrvAuthenticate
329 Func_t f = gSystem->DynFindSymbol(srvlib,"SrvAuthenticate");
330 if (f)
332 else {
333 Error("Authenticate", "can't find SrvAuthenticate");
334 return kFALSE;
335 }
336 //
337 // Locate SrvAuthCleanup
338 f = gSystem->DynFindSymbol(srvlib,"SrvAuthCleanup");
339 if (f)
341 else {
342 Warning("Authenticate", "can't find SrvAuthCleanup");
343 }
344 }
345
347 if (!confdir.Length()) {
348 Error("Authenticate", "config dir undefined");
349 return kFALSE;
350 }
351
352 // dir for temporary files
355 tmpdir = TString("/tmp");
356
357 // Get Host name
359 if (gDebug > 2)
360 Info("Authenticate","OpenHost = %s", openhost.Data());
361
362 // Run Authentication now
363 std::string user;
364 Int_t meth = -1;
365 Int_t auth = 0;
366 Int_t type = 0;
367 std::string ctkn = "";
368 if (fgSrvAuthHook)
369 auth = (*fgSrvAuthHook)(sock, confdir, tmpdir, user,
371
372 if (gDebug > 2)
373 Info("Authenticate","auth = %d, type= %d, ctkn= %s",
374 auth, type, ctkn.c_str());
375
376 return auth;
377}
#define SafeDelete(p)
Definition RConfig.hxx:538
#define f(i)
Definition RSha256.hxx:104
bool Bool_t
Definition RtypesCore.h:63
unsigned char UChar_t
Definition RtypesCore.h:38
constexpr Bool_t kFALSE
Definition RtypesCore.h:94
constexpr Bool_t kTRUE
Definition RtypesCore.h:93
#define ClassImp(name)
Definition Rtypes.h:374
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
Definition TROOT.cxx:622
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:414
static void SetAuthOpt(UChar_t &opt, UChar_t mod)
Kind of macro to parse input options Modify opt according to modifier mod.
TVirtualMutex * gSrvAuthenticateMutex
Int_t(* SrvClup_t)(TSeqCollection *)
const UChar_t kSrvNoAuth
const UChar_t kSrvAuth
Int_t(* SrvAuth_t)(TSocket *sock, const char *, const char *, std::string &, Int_t &, Int_t &, std::string &, TSeqCollection *)
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:572
#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:174
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition TNamed.cxx:150
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:205
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1057
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:864
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1071
void ResetBit(UInt_t f)
Definition TObject.h:204
static const TString & GetRootSys()
Get the rootsys directory in the installation. Static utility function.
Definition TROOT.cxx:3009
This class implements server sockets.
static SrvAuth_t fgSrvAuthHook
static UChar_t fgAcceptOpt
static void SetAcceptOptions(UChar_t Opt)
Set default options for Accept according to modifier 'mod'.
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.
static SrvClup_t fgSrvAuthClupHook
virtual ~TServerSocket()
Destructor: cleanup authentication stuff (if any) and close.
static void ShowAcceptOptions()
Print default options for Accept.
static UChar_t GetAcceptOptions()
Return default options for Accept.
virtual TSocket * Accept(UChar_t Opt=0)
Accept a connection on a server socket.
TInetAddress GetLocalInetAddress() override
Return internet address of host to which the server socket is bound, i.e.
TSeqCollection * fSecContexts
This class implements client sockets.
Definition TSocket.h:41
TInetAddress fAddress
Definition TSocket.h:59
Int_t fSocket
Definition TSocket.h:69
TSocket()
Definition TSocket.h:83
TString fService
Definition TSocket.h:67
@ kIsUnix
Definition TSocket.h:48
virtual void Close(Option_t *opt="")
Close the socket.
Definition TSocket.cxx:391
TInetAddress GetInetAddress() const
Definition TSocket.h:113
TSecContext * fSecContext
Definition TSocket.h:65
Basic string class.
Definition TString.h:139
virtual int GetServiceByName(const char *service)
Get port # of internet service.
Definition TSystem.cxx:2330
virtual TInetAddress GetSockName(int sock)
Get Internet Protocol (IP) address of host and port #.
Definition TSystem.cxx:2321
virtual Func_t DynFindSymbol(const char *module, const char *entry)
Find specific entry point in specified library.
Definition TSystem.cxx:2056
virtual char * GetServiceByPort(int port)
Get name of internet service.
Definition TSystem.cxx:2339
virtual int AcceptConnection(int sock)
Accept a connection.
Definition TSystem.cxx:2393
virtual TInetAddress GetPeerName(int sock)
Get Internet Protocol (IP) address of remote host and port #.
Definition TSystem.cxx:2312
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1869
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:1308
virtual int AnnounceUnixService(int port, int backlog)
Announce unix domain service.
Definition TSystem.cxx:2375
virtual int AnnounceTcpService(int port, Bool_t reuse, int backlog, int tcpwindowsize=-1, ESocketBindOption socketBindOption=ESocketBindOption::kInaddrAny)
Announce TCP/IP service.
Definition TSystem.cxx:2357
virtual const char * TempDirectory() const
Return a user configured or systemwide directory to create temporary files in.
Definition TSystem.cxx:1494
char * DynamicPathName(const char *lib, Bool_t quiet=kFALSE)
Find a dynamic library called lib using the system search paths.
Definition TSystem.cxx:2032
This class implements a mutex interface.
std::ostream & Info()
Definition hadd.cxx:171