1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
|
/************************************************************************************
PublicHeader: n/a
Filename : OVR_Session.h
Content : One network session that provides connection/disconnection events.
Created : June 10, 2014
Authors : Kevin Jenkins, Chris Taylor
Copyright : Copyright 2014 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#ifndef OVR_Session_h
#define OVR_Session_h
#include "OVR_Socket.h"
#include "OVR_PacketizedTCPSocket.h"
#include "../Kernel/OVR_Array.h"
#include "../Kernel/OVR_Threads.h"
#include "../Kernel/OVR_Atomic.h"
#include "../Kernel/OVR_RefCount.h"
namespace OVR { namespace Net {
class Session;
//-----------------------------------------------------------------------------
// Based on Semantic Versioning ( http://semver.org/ )
//
// Please update changelog below:
// 1.0.0 - [SDK 0.4.0] Initial version (July 21, 2014)
// 1.1.0 - Add Get/SetDriverMode_1, HMDCountUpdate_1
// Version mismatch results (July 28, 2014)
//-----------------------------------------------------------------------------
static const uint16_t RPCVersion_Major = 1; // MAJOR version when you make incompatible API changes,
static const uint16_t RPCVersion_Minor = 1; // MINOR version when you add functionality in a backwards-compatible manner, and
static const uint16_t RPCVersion_Patch = 0; // PATCH version when you make backwards-compatible bug fixes.
// Client starts communication by sending its version number.
struct RPC_C2S_Hello
{
RPC_C2S_Hello() :
MajorVersion(0),
MinorVersion(0),
PatchVersion(0)
{
}
String HelloString;
// Client version info
uint16_t MajorVersion, MinorVersion, PatchVersion;
void Serialize(Net::BitStream* bs)
{
bs->Write(HelloString);
bs->Write(MajorVersion);
bs->Write(MinorVersion);
bs->Write(PatchVersion);
}
bool Deserialize(Net::BitStream* bs)
{
bs->Read(HelloString);
bs->Read(MajorVersion);
bs->Read(MinorVersion);
return bs->Read(PatchVersion);
}
static void Generate(Net::BitStream* bs);
bool Validate();
};
// Server responds with an authorization accepted message, including the server's version number
struct RPC_S2C_Authorization
{
RPC_S2C_Authorization() :
MajorVersion(0),
MinorVersion(0),
PatchVersion(0)
{
}
String AuthString;
// Server version info
uint16_t MajorVersion, MinorVersion, PatchVersion;
void Serialize(Net::BitStream* bs)
{
bs->Write(AuthString);
bs->Write(MajorVersion);
bs->Write(MinorVersion);
bs->Write(PatchVersion);
}
bool Deserialize(Net::BitStream* bs)
{
bs->Read(AuthString);
bs->Read(MajorVersion);
bs->Read(MinorVersion);
return bs->Read(PatchVersion);
}
static void Generate(Net::BitStream* bs, String errorString = "");
bool Validate();
};
//-----------------------------------------------------------------------------
// Result of a session function
enum SessionResult
{
SessionResult_OK,
SessionResult_BindFailure,
SessionResult_ListenFailure,
SessionResult_ConnectFailure,
SessionResult_ConnectInProgress,
SessionResult_AlreadyConnected,
};
//-----------------------------------------------------------------------------
// Connection state
enum EConnectionState
{
State_Zombie, // Disconnected
// Client-only:
Client_Connecting, // Waiting for TCP connection
Client_ConnectedWait, // Connected! Waiting for server to authorize
// Server-only:
Server_ConnectedWait, // Connected! Waiting for client handshake
State_Connected // Connected
};
//-----------------------------------------------------------------------------
// Generic connection over any transport
class Connection : public RefCountBase<Connection>
{
public:
Connection() :
Transport(TransportType_None),
State(State_Zombie),
RemoteMajorVersion(0),
RemoteMinorVersion(0),
RemotePatchVersion(0)
{
}
virtual ~Connection() // Allow delete from base
{
}
public:
virtual void SetState(EConnectionState s) {State = s;}
TransportType Transport;
EConnectionState State;
// Version number read from remote host just before connection completes
int RemoteMajorVersion;
int RemoteMinorVersion;
int RemotePatchVersion;
};
//-----------------------------------------------------------------------------
// Generic network connection over any network transport
class NetworkConnection : public Connection
{
protected:
NetworkConnection()
{
}
virtual ~NetworkConnection()
{
}
public:
virtual void SetState(EConnectionState s)
{
if (s != State)
{
Mutex::Locker locker(&StateMutex);
if (s != State)
{
State = s;
if (State != Client_Connecting)
{
ConnectingWait.NotifyAll();
}
}
}
}
void WaitOnConnecting()
{
Mutex::Locker locker(&StateMutex);
while (State == Client_Connecting)
{
ConnectingWait.Wait(&StateMutex);
}
}
SockAddr Address;
Mutex StateMutex;
WaitCondition ConnectingWait;
};
//-----------------------------------------------------------------------------
// TCP Connection
class TCPConnection : public NetworkConnection
{
public:
TCPConnection()
{
}
virtual ~TCPConnection()
{
}
public:
Ptr<TCPSocket> pSocket;
};
//-----------------------------------------------------------------------------
// Packetized TCP Connection
class PacketizedTCPConnection : public TCPConnection
{
public:
PacketizedTCPConnection()
{
Transport = TransportType_PacketizedTCP;
}
virtual ~PacketizedTCPConnection()
{
}
};
//-----------------------------------------------------------------------------
// Generic socket listener description
class ListenerDescription
{
public:
ListenerDescription() :
Transport(TransportType_None)
{
}
TransportType Transport;
};
//-----------------------------------------------------------------------------
// Description for a Berkley socket listener
class BerkleyListenerDescription : public ListenerDescription
{
public:
static const int DefaultMaxIncomingConnections = 64;
static const int DefaultMaxConnections = 128;
BerkleyListenerDescription() :
MaxIncomingConnections(DefaultMaxIncomingConnections),
MaxConnections(DefaultMaxConnections)
{
}
Ptr<BerkleySocket> BoundSocketToListenWith;
int MaxIncomingConnections;
int MaxConnections;
};
//-----------------------------------------------------------------------------
// Receive payload
struct ReceivePayload
{
Connection* pConnection; // Source connection
uint8_t* pData; // Pointer to data received
int Bytes; // Number of bytes of data received
};
//-----------------------------------------------------------------------------
// Broadcast parameters
class BroadcastParameters
{
public:
BroadcastParameters() :
pData(NULL),
Bytes(0)
{
}
BroadcastParameters(const void* _pData, int _bytes) :
pData(_pData),
Bytes(_bytes)
{
}
public:
const void* pData; // Pointer to data to send
int Bytes; // Number of bytes of data received
};
//-----------------------------------------------------------------------------
// Send parameters
class SendParameters
{
public:
SendParameters() :
pData(NULL),
Bytes(0)
{
}
SendParameters(Ptr<Connection> _pConnection, const void* _pData, int _bytes) :
pConnection(_pConnection),
pData(_pData),
Bytes(_bytes)
{
}
public:
Ptr<Connection> pConnection; // Connection to use
const void* pData; // Pointer to data to send
int Bytes; // Number of bytes of data received
};
//-----------------------------------------------------------------------------
// Parameters to connect
struct ConnectParameters
{
public:
ConnectParameters() :
Transport(TransportType_None)
{
}
TransportType Transport;
};
struct ConnectParametersBerkleySocket : public ConnectParameters
{
SockAddr RemoteAddress;
Ptr<BerkleySocket> BoundSocketToConnectWith;
bool Blocking;
ConnectParametersBerkleySocket()
{
}
ConnectParametersBerkleySocket(Socket* s, SockAddr* addr) :
RemoteAddress(*addr)
{
BoundSocketToConnectWith = (BerkleySocket*)s;
}
};
//-----------------------------------------------------------------------------
// Listener receive result
enum ListenerReceiveResult
{
/// The SessionListener used this message and it shouldn't be given to the user.
LRR_RETURN = 0,
/// The SessionListener is going to hold on to this message. Do not deallocate it but do not pass it to other plugins either.
LRR_BREAK,
/// This message will be processed by other SessionListeners, and at last by the user.
LRR_CONTINUE,
};
//-----------------------------------------------------------------------------
// SessionListener
// Callback interface for network events such as connecting, disconnecting, getting data, independent of the transport medium
class SessionListener
{
public:
// Data events
virtual void OnReceive(ReceivePayload* pPayload, ListenerReceiveResult* lrrOut) { OVR_UNUSED2(pPayload, lrrOut); }
// Connection was closed
virtual void OnDisconnected(Connection* conn) = 0;
// Connection was created (some data was exchanged to verify protocol compatibility too)
virtual void OnConnected(Connection* conn) = 0;
// Server accepted client
virtual void OnNewIncomingConnection(Connection* conn) { OnConnected(conn); }
// Client was accepted
virtual void OnConnectionRequestAccepted(Connection* conn) { OnConnected(conn); }
// Connection attempt failed for some reason
virtual void OnConnectionAttemptFailed(Connection* conn) { OnDisconnected(conn); }
// Incompatible protocol
virtual void OnIncompatibleProtocol(Connection* conn) { OnConnectionAttemptFailed(conn); }
// Disconnected during initial handshake
virtual void OnHandshakeAttemptFailed(Connection* conn) { OnConnectionAttemptFailed(conn); }
// Other
virtual void OnAddedToSession(Session* session) { OVR_UNUSED(session); }
virtual void OnRemovedFromSession(Session* session) { OVR_UNUSED(session); }
};
//-----------------------------------------------------------------------------
// Session
// Interface for network events such as listening on a socket, sending data, connecting, and disconnecting. Works independently of the transport medium and also implements loopback
class Session : public SocketEvent_TCP, public NewOverrideBase
{
public:
Session() :
HasLoopbackListener(false)
{
}
virtual ~Session()
{
}
virtual SessionResult Listen(ListenerDescription* pListenerDescription);
virtual SessionResult Connect(ConnectParameters* cp);
virtual int Send(SendParameters* payload);
virtual void Broadcast(BroadcastParameters* payload);
virtual void Poll(bool listeners = true);
virtual void AddSessionListener(SessionListener* se);
virtual void RemoveSessionListener(SessionListener* se);
virtual SInt32 GetActiveSocketsCount();
// Packetized TCP convenience functions
virtual SessionResult ListenPTCP(BerkleyBindParameters* bbp);
virtual SessionResult ConnectPTCP(BerkleyBindParameters* bbp, SockAddr* RemoteAddress, bool blocking);
// Closes all the sockets; useful for interrupting the socket polling during shutdown
void Shutdown();
// Get count of successful connections (past handshake point)
int GetConnectionCount() const
{
return FullConnections.GetSizeI();
}
Ptr<Connection> GetConnectionAtIndex(int index);
protected:
virtual Ptr<Connection> AllocConnection(TransportType transportType);
Lock SocketListenersLock, ConnectionsLock, SessionListenersLock;
bool HasLoopbackListener; // Has loopback listener installed?
Array< Ptr<TCPSocket> > SocketListeners; // List of active sockets
Array< Ptr<Connection> > AllConnections; // List of active connections stuck at the versioning handshake
Array< Ptr<Connection> > FullConnections; // List of active connections past the versioning handshake
Array< SessionListener* > SessionListeners; // List of session listeners
// Tools
Ptr<PacketizedTCPConnection> findConnectionBySocket(Array< Ptr<Connection> >& connectionArray, Socket* s, int *connectionIndex = NULL); // Call with ConnectionsLock held
Ptr<PacketizedTCPConnection> findConnectionBySockAddr(SockAddr* address); // Call with ConnectionsLock held
int invokeSessionListeners(ReceivePayload*);
void invokeSessionEvent(void(SessionListener::*f)(Connection*), Connection* pConnection);
// TCP
virtual void TCP_OnRecv(Socket* pSocket, uint8_t* pData, int bytesRead);
virtual void TCP_OnClosed(TCPSocket* pSocket);
virtual void TCP_OnAccept(TCPSocket* pListener, SockAddr* pSockAddr, SocketHandle newSock);
virtual void TCP_OnConnected(TCPSocket* pSocket);
};
}} // OVR::Net
#endif
|