Source code

Revision control

Other Tools

1
/* vim:set ts=4 sw=2 sts=2 ci et: */
2
/* This Source Code Form is subject to the terms of the Mozilla Public
3
* License, v. 2.0. If a copy of the MPL was not distributed with this
4
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6
#ifndef nsSocketTransportService2_h__
7
#define nsSocketTransportService2_h__
8
9
#include "nsPISocketTransportService.h"
10
#include "nsIThreadInternal.h"
11
#include "nsIRunnable.h"
12
#include "nsCOMPtr.h"
13
#include "prinrval.h"
14
#include "mozilla/Logging.h"
15
#include "prinit.h"
16
#include "nsIObserver.h"
17
#include "mozilla/LinkedList.h"
18
#include "mozilla/Mutex.h"
19
#include "mozilla/net/DashboardTypes.h"
20
#include "mozilla/Atomics.h"
21
#include "mozilla/TimeStamp.h"
22
#include "nsITimer.h"
23
#include "mozilla/UniquePtr.h"
24
#include "PollableEvent.h"
25
26
class nsASocketHandler;
27
struct PRPollDesc;
28
class nsIPrefBranch;
29
30
//-----------------------------------------------------------------------------
31
32
namespace mozilla {
33
namespace net {
34
35
//
36
// set MOZ_LOG=nsSocketTransport:5
37
//
38
extern LazyLogModule gSocketTransportLog;
39
#define SOCKET_LOG(args) MOZ_LOG(gSocketTransportLog, LogLevel::Debug, args)
40
#define SOCKET_LOG1(args) MOZ_LOG(gSocketTransportLog, LogLevel::Error, args)
41
#define SOCKET_LOG_ENABLED() MOZ_LOG_TEST(gSocketTransportLog, LogLevel::Debug)
42
43
//
44
// set MOZ_LOG=UDPSocket:5
45
//
46
extern LazyLogModule gUDPSocketLog;
47
#define UDPSOCKET_LOG(args) MOZ_LOG(gUDPSocketLog, LogLevel::Debug, args)
48
#define UDPSOCKET_LOG_ENABLED() MOZ_LOG_TEST(gUDPSocketLog, LogLevel::Debug)
49
50
//-----------------------------------------------------------------------------
51
52
#define NS_SOCKET_POLL_TIMEOUT PR_INTERVAL_NO_TIMEOUT
53
54
//-----------------------------------------------------------------------------
55
56
// These maximums are borrowed from the linux kernel.
57
static const int32_t kMaxTCPKeepIdle = 32767; // ~9 hours.
58
static const int32_t kMaxTCPKeepIntvl = 32767;
59
static const int32_t kMaxTCPKeepCount = 127;
60
static const int32_t kDefaultTCPKeepCount =
61
#if defined(XP_WIN)
62
10; // Hardcoded in Windows.
63
#elif defined(XP_MACOSX)
64
8; // Hardcoded in OSX.
65
#else
66
4; // Specifiable in Linux.
67
#endif
68
69
class LinkedRunnableEvent final
70
: public LinkedListElement<LinkedRunnableEvent> {
71
public:
72
explicit LinkedRunnableEvent(nsIRunnable* event) : mEvent(event) {}
73
~LinkedRunnableEvent() = default;
74
75
already_AddRefed<nsIRunnable> TakeEvent() { return mEvent.forget(); }
76
77
private:
78
nsCOMPtr<nsIRunnable> mEvent;
79
};
80
81
//-----------------------------------------------------------------------------
82
83
class nsSocketTransportService final : public nsPISocketTransportService,
84
public nsISerialEventTarget,
85
public nsIThreadObserver,
86
public nsIRunnable,
87
public nsIObserver {
88
public:
89
NS_DECL_THREADSAFE_ISUPPORTS
90
NS_DECL_NSPISOCKETTRANSPORTSERVICE
91
NS_DECL_NSISOCKETTRANSPORTSERVICE
92
NS_DECL_NSIROUTEDSOCKETTRANSPORTSERVICE
93
NS_DECL_NSIEVENTTARGET_FULL
94
NS_DECL_NSITHREADOBSERVER
95
NS_DECL_NSIRUNNABLE
96
NS_DECL_NSIOBSERVER
97
98
nsSocketTransportService();
99
100
// Max Socket count may need to get initialized/used by nsHttpHandler
101
// before this class is initialized.
102
static uint32_t gMaxCount;
103
static PRCallOnceType gMaxCountInitOnce;
104
static PRStatus DiscoverMaxCount();
105
106
bool CanAttachSocket();
107
108
// Called by the networking dashboard on the socket thread only
109
// Fills the passed array with socket information
110
void GetSocketConnections(nsTArray<SocketInfo>*);
111
uint64_t GetSentBytes() { return mSentBytesCount; }
112
uint64_t GetReceivedBytes() { return mReceivedBytesCount; }
113
114
// Returns true if keepalives are enabled in prefs.
115
bool IsKeepaliveEnabled() { return mKeepaliveEnabledPref; }
116
117
bool IsTelemetryEnabledAndNotSleepPhase();
118
PRIntervalTime MaxTimeForPrClosePref() { return mMaxTimeForPrClosePref; }
119
120
bool IsEsniEnabled() {
121
return mEsniEnabled && !mTrustedMitmDetected && !mNotTrustedMitmDetected;
122
}
123
124
void SetNotTrustedMitmDetected() { mNotTrustedMitmDetected = true; }
125
126
protected:
127
virtual ~nsSocketTransportService();
128
129
private:
130
//-------------------------------------------------------------------------
131
// misc (any thread)
132
//-------------------------------------------------------------------------
133
134
nsCOMPtr<nsIThread> mThread; // protected by mLock
135
UniquePtr<PollableEvent> mPollableEvent;
136
137
// Returns mThread, protecting the get-and-addref with mLock
138
already_AddRefed<nsIThread> GetThreadSafely();
139
140
//-------------------------------------------------------------------------
141
// initialization and shutdown (any thread)
142
//-------------------------------------------------------------------------
143
144
Mutex mLock;
145
bool mInitialized;
146
bool mShuttingDown;
147
// indicates whether we are currently in the
148
// process of shutting down
149
bool mOffline;
150
bool mGoingOffline;
151
152
// Detaches all sockets.
153
void Reset(bool aGuardLocals);
154
155
nsresult ShutdownThread();
156
157
//-------------------------------------------------------------------------
158
// socket lists (socket thread only)
159
//
160
// only "active" sockets are on the poll list. the active list is kept
161
// in sync with the poll list such that:
162
//
163
// mActiveList[k].mFD == mPollList[k+1].fd
164
//
165
// where k=0,1,2,...
166
//-------------------------------------------------------------------------
167
168
struct SocketContext {
169
PRFileDesc* mFD;
170
nsASocketHandler* mHandler;
171
PRIntervalTime mPollStartEpoch; // time we started to poll this socket
172
173
public:
174
// Returns true iff the socket has not been signalled longer than
175
// the desired timeout (mHandler->mPollTimeout).
176
bool IsTimedOut(PRIntervalTime now) const;
177
// Engages the timeout by marking the epoch we start polling this socket.
178
// If epoch is already marked this does nothing, hence, this method can be
179
// called everytime we put this socket to poll() list with in-flags set.
180
void EnsureTimeout(PRIntervalTime now);
181
// Called after an event on a socket has been signalled to turn of the
182
// timeout calculation.
183
void DisengageTimeout();
184
// Returns the number of intervals this socket is about to timeout in,
185
// or 0 (zero) when it has already timed out. Returns
186
// NS_SOCKET_POLL_TIMEOUT when there is no timeout set on the socket.
187
PRIntervalTime TimeoutIn(PRIntervalTime now) const;
188
// When a socket timeout is reset and later set again, it may happen
189
// that mPollStartEpoch is not reset in between. We have to manually
190
// call this on every iteration over sockets to ensure the epoch reset.
191
void MaybeResetEpoch();
192
};
193
194
SocketContext* mActiveList; /* mListSize entries */
195
SocketContext* mIdleList; /* mListSize entries */
196
nsIThread* mRawThread;
197
198
uint32_t mActiveListSize;
199
uint32_t mIdleListSize;
200
uint32_t mActiveCount;
201
uint32_t mIdleCount;
202
203
nsresult DetachSocket(SocketContext*, SocketContext*);
204
nsresult AddToIdleList(SocketContext*);
205
nsresult AddToPollList(SocketContext*);
206
void RemoveFromIdleList(SocketContext*);
207
void RemoveFromPollList(SocketContext*);
208
void MoveToIdleList(SocketContext* sock);
209
void MoveToPollList(SocketContext* sock);
210
211
bool GrowActiveList();
212
bool GrowIdleList();
213
void InitMaxCount();
214
215
// Total bytes number transfered through all the sockets except active ones
216
uint64_t mSentBytesCount;
217
uint64_t mReceivedBytesCount;
218
//-------------------------------------------------------------------------
219
// poll list (socket thread only)
220
//
221
// first element of the poll list is mPollableEvent (or null if the pollable
222
// event cannot be created).
223
//-------------------------------------------------------------------------
224
225
PRPollDesc* mPollList; /* mListSize + 1 entries */
226
227
PRIntervalTime PollTimeout(
228
PRIntervalTime now); // computes ideal poll timeout
229
nsresult DoPollIteration(TimeDuration* pollDuration);
230
// perfoms a single poll iteration
231
int32_t Poll(TimeDuration* pollDuration, PRIntervalTime now);
232
// calls PR_Poll. the out param
233
// interval indicates the poll
234
// duration in seconds.
235
// pollDuration is used only for
236
// telemetry
237
238
//-------------------------------------------------------------------------
239
// pending socket queue - see NotifyWhenCanAttachSocket
240
//-------------------------------------------------------------------------
241
AutoCleanLinkedList<LinkedRunnableEvent> mPendingSocketQueue;
242
243
// Preference Monitor for SendBufferSize and Keepalive prefs.
244
nsresult UpdatePrefs();
245
static void PrefCallback(const char* aPref, nsSocketTransportService* aSelf);
246
void UpdateSendBufferPref();
247
int32_t mSendBufferSize;
248
// Number of seconds of connection is idle before first keepalive ping.
249
int32_t mKeepaliveIdleTimeS;
250
// Number of seconds between retries should keepalive pings fail.
251
int32_t mKeepaliveRetryIntervalS;
252
// Number of keepalive probes to send.
253
int32_t mKeepaliveProbeCount;
254
// True if TCP keepalive is enabled globally.
255
bool mKeepaliveEnabledPref;
256
// Timeout of pollable event signalling.
257
TimeDuration mPollableEventTimeout;
258
259
Atomic<bool> mServingPendingQueue;
260
Atomic<int32_t, Relaxed> mMaxTimePerPollIter;
261
Atomic<PRIntervalTime, Relaxed> mMaxTimeForPrClosePref;
262
// Timestamp of the last network link change event, tracked
263
// also on child processes.
264
Atomic<PRIntervalTime, Relaxed> mLastNetworkLinkChangeTime;
265
// Preference for how long we do busy wait after network link
266
// change has been detected.
267
Atomic<PRIntervalTime, Relaxed> mNetworkLinkChangeBusyWaitPeriod;
268
// Preference for the value of timeout for poll() we use during
269
// the network link change event period.
270
Atomic<PRIntervalTime, Relaxed> mNetworkLinkChangeBusyWaitTimeout;
271
272
// Between a computer going to sleep and waking up the PR_*** telemetry
273
// will be corrupted - so do not record it.
274
Atomic<bool, Relaxed> mSleepPhase;
275
nsCOMPtr<nsITimer> mAfterWakeUpTimer;
276
277
void OnKeepaliveEnabledPrefChange();
278
void NotifyKeepaliveEnabledPrefChange(SocketContext* sock);
279
280
// Socket thread only for dynamically adjusting max socket size
281
#if defined(XP_WIN)
282
void ProbeMaxCount();
283
#endif
284
bool mProbedMaxCount;
285
286
void AnalyzeConnection(nsTArray<SocketInfo>* data, SocketContext* context,
287
bool aActive);
288
289
void ClosePrivateConnections();
290
void DetachSocketWithGuard(bool aGuardLocals, SocketContext* socketList,
291
int32_t index);
292
293
void MarkTheLastElementOfPendingQueue();
294
295
#if defined(XP_WIN)
296
Atomic<bool> mPolling;
297
nsCOMPtr<nsITimer> mPollRepairTimer;
298
void StartPollWatchdog();
299
void DoPollRepair();
300
void StartPolling();
301
void EndPolling();
302
#endif
303
304
void TryRepairPollableEvent();
305
306
bool mEsniEnabled;
307
bool mTrustedMitmDetected;
308
bool mNotTrustedMitmDetected;
309
};
310
311
extern nsSocketTransportService* gSocketTransportService;
312
bool OnSocketThread();
313
314
} // namespace net
315
} // namespace mozilla
316
317
#endif // !nsSocketTransportService_h__