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// //
14// TServerSocket //
15// //
16// This class implements server sockets. A server socket waits for //
17// requests to come in over the network. It performs some operation //
18// based on that request and then possibly returns a full duplex socket //
19// to the requester. The actual work is done via the TSystem class //
20// (either TUnixSystem or TWinNTSystem). //
21// //
22//////////////////////////////////////////////////////////////////////////
23
24#include "TServerSocket.h"
25#include "TSocket.h"
26#include "TSystem.h"
27#include "TROOT.h"
28#include "TError.h"
29#include <string>
30#include "TVirtualMutex.h"
31
32// Hook to server authentication wrapper
35
36// Defaul options for accept
38
40
41
42////////////////////////////////////////////////////////////////////////////////
43/// Kind of macro to parse input options
44/// Modify opt according to modifier mod.
45
46static void SetAuthOpt(UChar_t &opt, UChar_t mod)
47{
49
50 if (!mod) return;
51
52 if ((mod & kSrvAuth)) opt |= kSrvAuth;
53 if ((mod & kSrvNoAuth)) opt &= ~kSrvAuth;
54}
55
56////////////////////////////////////////////////////////////////////////////////
57/// Create a server socket object for a named service. Set reuse to true
58/// to force reuse of the server socket (i.e. do not wait for the time
59/// out to pass). Using backlog one can set the desirable queue length
60/// for pending connections.
61/// Use tcpwindowsize to specify the size of the receive buffer, it has
62/// to be specified here to make sure the window scale option is set (for
63/// tcpwindowsize > 65KB and for platforms supporting window scaling).
64/// The socketBindOption parameter allows to specify how the socket will be
65/// bound. See the documentation of ESocketBindOption for the details.
66/// Use IsValid() to check the validity of the
67/// server socket. In case server socket is not valid use GetErrorCode()
68/// to obtain the specific error value. These values are:
69/// 0 = no error (socket is valid)
70/// -1 = low level socket() call failed
71/// -2 = low level bind() call failed
72/// -3 = low level listen() call failed
73/// Every valid server socket is added to the TROOT sockets list which
74/// will make sure that any open sockets are properly closed on
75/// program termination.
76
79{
82
83 SetName("ServerSocket");
84
85 fSecContext = 0;
86 fSecContexts = new TList;
87
88 // If this is a local path, try announcing a UNIX socket service
92 service[0] == '/')) {
93#else
94 service[0] == '/' || (service[1] == ':' && service[2] == '/'))) {
95#endif
97 fService = "unix:";
100 if (fSocket >= 0) {
102 gROOT->GetListOfSockets()->Add(this);
103 }
104 } else {
105 // TCP / UDP socket
107 int port = gSystem->GetServiceByName(service);
108 if (port != -1) {
110 if (fSocket >= 0) {
112 gROOT->GetListOfSockets()->Add(this);
113 }
114 } else {
115 fSocket = -1;
116 }
117 }
118}
119
120////////////////////////////////////////////////////////////////////////////////
121/// Create a server socket object on a specified port. Set reuse to true
122/// to force reuse of the server socket (i.e. do not wait for the time
123/// out to pass). Using backlog one can set the desirable queue length
124/// for pending connections. If port is 0 a port scan will be done to
125/// find a free port. This option is mutual exlusive with the reuse option.
126/// Use tcpwindowsize to specify the size of the receive buffer, it has
127/// to be specified here to make sure the window scale option is set (for
128/// tcpwindowsize > 65KB and for platforms supporting window scaling).
129/// The socketBindOption parameter allows to specify how the socket will be
130/// bound. See the documentation of ESocketBindOption for the details.
131/// Use IsValid() to check the validity of the
132/// server socket. In case server socket is not valid use GetErrorCode()
133/// to obtain the specific error value. These values are:
134/// 0 = no error (socket is valid)
135/// -1 = low level socket() call failed
136/// -2 = low level bind() call failed
137/// -3 = low level listen() call failed
138/// Every valid server socket is added to the TROOT sockets list which
139/// will make sure that any open sockets are properly closed on
140/// program termination.
141
144{
147
148 SetName("ServerSocket");
149
150 fSecContext = 0;
151 fSecContexts = new TList;
154
156 if (fSocket >= 0) {
158 gROOT->GetListOfSockets()->Add(this);
159 }
160}
161
162////////////////////////////////////////////////////////////////////////////////
163/// Destructor: cleanup authentication stuff (if any) and close
164
166{
168 if (fSecContexts) {
169 if (fgSrvAuthClupHook) {
170 // Cleanup the security contexts
171 (*fgSrvAuthClupHook)(fSecContexts);
172 }
173 // Remove the list
176 fSecContexts = 0;
177 }
178
179 Close();
180}
181
182////////////////////////////////////////////////////////////////////////////////
183/// Accept a connection on a server socket. Returns a full-duplex
184/// communication TSocket object. If no pending connections are
185/// present on the queue and nonblocking mode has not been enabled
186/// with SetOption(kNoBlock,1) the call blocks until a connection is
187/// present. The returned socket must be deleted by the user. The socket
188/// is also added to the TROOT sockets list which will make sure that
189/// any open sockets are properly closed on program termination.
190/// In case of error 0 is returned and in case non-blocking I/O is
191/// enabled and no connections are available -1 is returned.
192///
193/// The opt can be used to require client authentication; valid options are
194///
195/// kSrvAuth = require client authentication
196/// kSrvNoAuth = force no client authentication
197///
198/// Example: use Opt = kSrvAuth to require client authentication.
199///
200/// Default options are taken from fgAcceptOpt and are initially
201/// equivalent to kSrvNoAuth; they can be changed with the static
202/// method TServerSocket::SetAcceptOptions(Opt).
203/// The active defaults can be visualized using the static method
204/// TServerSocket::ShowAcceptOptions().
205///
206
208{
209 if (fSocket == -1) { return 0; }
210
211 TSocket *socket = new TSocket;
212
214 if (soc == -1) { delete socket; return 0; }
215 if (soc == -2) { delete socket; return (TSocket*) -1; }
216
217 // Parse Opt
219 SetAuthOpt(acceptOpt, opt);
221
222 socket->fSocket = soc;
223 socket->fSecContext = 0;
224 socket->fService = fService;
226 socket->fAddress = gSystem->GetPeerName(socket->fSocket);
227 if (socket->fSocket >= 0) {
229 gROOT->GetListOfSockets()->Add(socket);
230 }
231
232 // Perform authentication, if required
233 if (auth) {
234 if (!Authenticate(socket)) {
235 delete socket;
236 socket = 0;
237 }
238 }
239
240 return socket;
241}
242
243////////////////////////////////////////////////////////////////////////////////
244/// Return internet address of host to which the server socket is bound,
245/// i.e. the local host. In case of error TInetAddress::IsValid() returns
246/// kFALSE.
247
249{
250 if (fSocket != -1) {
251 if (fAddress.GetPort() == -1)
253 return fAddress;
254 }
255 return TInetAddress();
256}
257
258////////////////////////////////////////////////////////////////////////////////
259/// Get port # to which server socket is bound. In case of error returns -1.
260
262{
263 if (fSocket != -1) {
264 if (fAddress.GetPort() == -1)
266 return fAddress.GetPort();
267 }
268 return -1;
269}
270
271
272////////////////////////////////////////////////////////////////////////////////
273/// Return default options for Accept
274
279
280////////////////////////////////////////////////////////////////////////////////
281/// Set default options for Accept according to modifier 'mod'.
282/// Use:
283/// kSrvAuth require client authentication
284/// kSrvNoAuth do not require client authentication
285
290
291////////////////////////////////////////////////////////////////////////////////
292/// Print default options for Accept.
293
295{
296 ::Info("ShowAcceptOptions", "Use authentication: %s", (fgAcceptOpt & kSrvAuth) ? "yes" : "no");
297}
298
299////////////////////////////////////////////////////////////////////////////////
300/// Check authentication request from the client on new
301/// open connection
302
304{
305 if (!fgSrvAuthHook) {
307
308 // Load libraries needed for (server) authentication ...
309 TString srvlib = "libSrvAuth";
310 char *p = 0;
311 // The generic one
312 if ((p = gSystem->DynamicPathName(srvlib, kTRUE))) {
313 delete[] p;
314 if (gSystem->Load(srvlib) == -1) {
315 Error("Authenticate", "can't load %s",srvlib.Data());
316 return kFALSE;
317 }
318 } else {
319 Error("Authenticate", "can't locate %s",srvlib.Data());
320 return kFALSE;
321 }
322 //
323 // Locate SrvAuthenticate
324 Func_t f = gSystem->DynFindSymbol(srvlib,"SrvAuthenticate");
325 if (f)
327 else {
328 Error("Authenticate", "can't find SrvAuthenticate");
329 return kFALSE;
330 }
331 //
332 // Locate SrvAuthCleanup
333 f = gSystem->DynFindSymbol(srvlib,"SrvAuthCleanup");
334 if (f)
336 else {
337 Warning("Authenticate", "can't find SrvAuthCleanup");
338 }
339 }
340
342 if (!confdir.Length()) {
343 Error("Authenticate", "config dir undefined");
344 return kFALSE;
345 }
346
347 // dir for temporary files
350 tmpdir = TString("/tmp");
351
352 // Get Host name
354 if (gDebug > 2)
355 Info("Authenticate","OpenHost = %s", openhost.Data());
356
357 // Run Authentication now
358 std::string user;
359 Int_t meth = -1;
360 Int_t auth = 0;
361 Int_t type = 0;
362 std::string ctkn = "";
363 if (fgSrvAuthHook)
364 auth = (*fgSrvAuthHook)(sock, confdir, tmpdir, user,
366
367 if (gDebug > 2)
368 Info("Authenticate","auth = %d, type= %d, ctkn= %s",
369 auth, type, ctkn.c_str());
370
371 return auth;
372}
#define SafeDelete(p)
Definition RConfig.hxx:533
#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:627
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:411
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: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:202
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:201
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1045
static const TString & GetRootSys()
Get the rootsys directory in the installation. Static utility function.
Definition TROOT.cxx:2986
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
TInetAddress fAddress
Definition TSocket.h:57
Int_t fSocket
Definition TSocket.h:67
TSocket()
Definition TSocket.h:81
TString fService
Definition TSocket.h:65
@ kIsUnix
Definition TSocket.h:46
virtual void Close(Option_t *opt="")
Close the socket.
Definition TSocket.cxx:380
TInetAddress GetInetAddress() const
Definition TSocket.h:111
TSecContext * fSecContext
Definition TSocket.h:63
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.