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/. */
6 #ifndef nsSocketTransportService2_h__
7 #define nsSocketTransportService2_h__
9 #include "PollableEvent.h"
10 #include "mozilla/Atomics.h"
11 #include "mozilla/LinkedList.h"
12 #include "mozilla/Logging.h"
13 #include "mozilla/Maybe.h"
14 #include "mozilla/Mutex.h"
15 #include "mozilla/TimeStamp.h"
17 #include "mozilla/UniquePtr.h"
18 #include "mozilla/net/DashboardTypes.h"
20 #include "nsASocketHandler.h"
21 #include "nsIDirectTaskDispatcher.h"
22 #include "nsIObserver.h"
23 #include "nsIRunnable.h"
24 #include "nsIThreadInternal.h"
26 #include "nsPISocketTransportService.h"
33 //-----------------------------------------------------------------------------
39 // set MOZ_LOG=nsSocketTransport:5
41 extern LazyLogModule gSocketTransportLog
;
42 #define SOCKET_LOG(args) MOZ_LOG(gSocketTransportLog, LogLevel::Debug, args)
43 #define SOCKET_LOG1(args) MOZ_LOG(gSocketTransportLog, LogLevel::Error, args)
44 #define SOCKET_LOG_ENABLED() MOZ_LOG_TEST(gSocketTransportLog, LogLevel::Debug)
47 // set MOZ_LOG=UDPSocket:5
49 extern LazyLogModule gUDPSocketLog
;
50 #define UDPSOCKET_LOG(args) MOZ_LOG(gUDPSocketLog, LogLevel::Debug, args)
51 #define UDPSOCKET_LOG_ENABLED() MOZ_LOG_TEST(gUDPSocketLog, LogLevel::Debug)
53 //-----------------------------------------------------------------------------
55 #define NS_SOCKET_POLL_TIMEOUT PR_INTERVAL_NO_TIMEOUT
57 //-----------------------------------------------------------------------------
59 // These maximums are borrowed from the linux kernel.
60 static const int32_t kMaxTCPKeepIdle
= 32767; // ~9 hours.
61 static const int32_t kMaxTCPKeepIntvl
= 32767;
62 static const int32_t kMaxTCPKeepCount
= 127;
63 static const int32_t kDefaultTCPKeepCount
=
65 10; // Hardcoded in Windows.
66 #elif defined(XP_MACOSX)
67 8; // Hardcoded in OSX.
69 4; // Specifiable in Linux.
72 class LinkedRunnableEvent final
73 : public LinkedListElement
<LinkedRunnableEvent
> {
75 explicit LinkedRunnableEvent(nsIRunnable
* event
) : mEvent(event
) {}
76 ~LinkedRunnableEvent() = default;
78 already_AddRefed
<nsIRunnable
> TakeEvent() { return mEvent
.forget(); }
81 nsCOMPtr
<nsIRunnable
> mEvent
;
84 //-----------------------------------------------------------------------------
86 class nsSocketTransportService final
: public nsPISocketTransportService
,
87 public nsISerialEventTarget
,
88 public nsIThreadObserver
,
92 public nsIDirectTaskDispatcher
{
94 NS_DECL_THREADSAFE_ISUPPORTS
95 NS_DECL_NSPISOCKETTRANSPORTSERVICE
96 NS_DECL_NSISOCKETTRANSPORTSERVICE
97 NS_DECL_NSIROUTEDSOCKETTRANSPORTSERVICE
98 NS_DECL_NSIEVENTTARGET_FULL
99 NS_DECL_NSITHREADOBSERVER
103 NS_DECL_NSIDIRECTTASKDISPATCHER
105 static const uint32_t SOCKET_LIMIT_MIN
= 50U;
107 nsSocketTransportService();
109 // Max Socket count may need to get initialized/used by nsHttpHandler
110 // before this class is initialized.
111 static uint32_t gMaxCount
;
112 static PRCallOnceType gMaxCountInitOnce
;
113 static PRStatus
DiscoverMaxCount();
115 bool CanAttachSocket();
117 // Called by the networking dashboard on the socket thread only
118 // Fills the passed array with socket information
119 void GetSocketConnections(nsTArray
<SocketInfo
>*);
120 uint64_t GetSentBytes() { return mSentBytesCount
; }
121 uint64_t GetReceivedBytes() { return mReceivedBytesCount
; }
123 // Returns true if keepalives are enabled in prefs.
124 bool IsKeepaliveEnabled() { return mKeepaliveEnabledPref
; }
126 bool IsTelemetryEnabledAndNotSleepPhase();
127 PRIntervalTime
MaxTimeForPrClosePref() { return mMaxTimeForPrClosePref
; }
129 // According the preference value of `network.socket.forcePort` this method
130 // possibly remaps the port number passed as the arg.
131 void ApplyPortRemap(uint16_t* aPort
);
133 // Reads the preference string and updates (rewrites) the mPortRemapping
134 // array on the socket thread. Returns true if the whole pref string was
136 bool UpdatePortRemapPreference(nsACString
const& aPortMappingPref
);
139 virtual ~nsSocketTransportService();
142 //-------------------------------------------------------------------------
144 //-------------------------------------------------------------------------
146 // The value is guaranteed to be valid and not dangling while on the socket
147 // thread as mThread is only ever reset after it's been shutdown.
148 // This member should only ever be read on the socket thread.
149 nsIThread
* mRawThread
{nullptr};
151 // Returns mThread in a thread-safe manner.
152 already_AddRefed
<nsIThread
> GetThreadSafely();
153 // Same as above, but return mThread as a nsIDirectTaskDispatcher
154 already_AddRefed
<nsIDirectTaskDispatcher
> GetDirectTaskDispatcherSafely();
156 //-------------------------------------------------------------------------
157 // initialization and shutdown (any thread)
158 //-------------------------------------------------------------------------
160 Atomic
<bool> mInitialized
{false};
161 // indicates whether we are currently in the process of shutting down
162 Atomic
<bool> mShuttingDown
{false};
164 Mutex mLock
{"nsSocketTransportService::mLock"};
165 // Variables in the next section protected by mLock
167 // mThread and mDirectTaskDispatcher are only ever modified on the main
168 // thread. Will be set on Init and set to null after shutdown. You must access
169 // mThread and mDirectTaskDispatcher outside the main thread via respectively
170 // GetThreadSafely and GetDirectTaskDispatchedSafely().
171 nsCOMPtr
<nsIThread
> mThread
MOZ_GUARDED_BY(mLock
);
172 // We store a pointer to mThread as a direct task dispatcher to avoid having
173 // to do do_QueryInterface whenever we need to access the interface.
174 nsCOMPtr
<nsIDirectTaskDispatcher
> mDirectTaskDispatcher
MOZ_GUARDED_BY(mLock
);
175 UniquePtr
<PollableEvent
> mPollableEvent
MOZ_GUARDED_BY(mLock
);
176 bool mOffline
MOZ_GUARDED_BY(mLock
) = false;
177 bool mGoingOffline
MOZ_GUARDED_BY(mLock
) = false;
179 // Detaches all sockets.
180 void Reset(bool aGuardLocals
);
182 nsresult
ShutdownThread();
184 //-------------------------------------------------------------------------
185 // socket lists (socket thread only)
187 // only "active" sockets are on the poll list. the active list is kept
188 // in sync with the poll list such that:
190 // mActiveList[k].mFD == mPollList[k+1].fd
193 //-------------------------------------------------------------------------
195 class SocketContext
{
197 SocketContext(PRFileDesc
* aFD
,
198 already_AddRefed
<nsASocketHandler
>&& aHandler
,
199 PRIntervalTime aPollStartEpoch
)
200 : mFD(aFD
), mHandler(aHandler
), mPollStartEpoch(aPollStartEpoch
) {}
201 SocketContext(PRFileDesc
* aFD
, nsASocketHandler
* aHandler
,
202 PRIntervalTime aPollStartEpoch
)
203 : mFD(aFD
), mHandler(aHandler
), mPollStartEpoch(aPollStartEpoch
) {}
204 ~SocketContext() = default;
206 // Returns true iff the socket has not been signalled longer than
207 // the desired timeout (mHandler->mPollTimeout).
208 bool IsTimedOut(PRIntervalTime now
) const;
209 // Engages the timeout by marking the epoch we start polling this socket.
210 // If epoch is already marked this does nothing, hence, this method can be
211 // called everytime we put this socket to poll() list with in-flags set.
212 void EnsureTimeout(PRIntervalTime now
);
213 // Called after an event on a socket has been signalled to turn of the
214 // timeout calculation.
215 void DisengageTimeout();
216 // Returns the number of intervals this socket is about to timeout in,
217 // or 0 (zero) when it has already timed out. Returns
218 // NS_SOCKET_POLL_TIMEOUT when there is no timeout set on the socket.
219 PRIntervalTime
TimeoutIn(PRIntervalTime now
) const;
220 // When a socket timeout is reset and later set again, it may happen
221 // that mPollStartEpoch is not reset in between. We have to manually
222 // call this on every iteration over sockets to ensure the epoch reset.
223 void MaybeResetEpoch();
226 RefPtr
<nsASocketHandler
> mHandler
;
227 PRIntervalTime mPollStartEpoch
; // time we started to poll this socket
230 using SocketContextList
= AutoTArray
<SocketContext
, SOCKET_LIMIT_MIN
>;
231 int64_t SockIndex(SocketContextList
& aList
, SocketContext
* aSock
);
233 SocketContextList mActiveList
;
234 SocketContextList mIdleList
;
236 nsresult
DetachSocket(SocketContextList
& listHead
, SocketContext
*);
237 void AddToIdleList(SocketContext
* sock
);
238 void AddToPollList(SocketContext
* sock
);
239 void RemoveFromIdleList(SocketContext
* sock
);
240 void RemoveFromPollList(SocketContext
* sock
);
241 void MoveToIdleList(SocketContext
* sock
);
242 void MoveToPollList(SocketContext
* sock
);
246 // Total bytes number transfered through all the sockets except active ones
247 uint64_t mSentBytesCount
{0};
248 uint64_t mReceivedBytesCount
{0};
249 //-------------------------------------------------------------------------
250 // poll list (socket thread only)
252 // first element of the poll list is mPollableEvent (or null if the pollable
253 // event cannot be created).
254 //-------------------------------------------------------------------------
256 nsTArray
<PRPollDesc
> mPollList
;
258 PRIntervalTime
PollTimeout(
259 PRIntervalTime now
); // computes ideal poll timeout
260 nsresult
DoPollIteration(TimeDuration
* pollDuration
);
261 // perfoms a single poll iteration
262 int32_t Poll(TimeDuration
* pollDuration
, PRIntervalTime ts
);
263 // calls PR_Poll. the out param
264 // interval indicates the poll
265 // duration in seconds.
266 // pollDuration is used only for
269 //-------------------------------------------------------------------------
270 // pending socket queue - see NotifyWhenCanAttachSocket
271 //-------------------------------------------------------------------------
272 AutoCleanLinkedList
<LinkedRunnableEvent
> mPendingSocketQueue
;
274 // Preference Monitor for SendBufferSize and Keepalive prefs.
275 nsresult
UpdatePrefs();
276 static void UpdatePrefs(const char* aPref
, void* aSelf
);
277 void UpdateSendBufferPref();
278 int32_t mSendBufferSize
{0};
279 // Number of seconds of connection is idle before first keepalive ping.
280 int32_t mKeepaliveIdleTimeS
{600};
281 // Number of seconds between retries should keepalive pings fail.
282 int32_t mKeepaliveRetryIntervalS
{1};
283 // Number of keepalive probes to send.
284 int32_t mKeepaliveProbeCount
{kDefaultTCPKeepCount
};
285 // True if TCP keepalive is enabled globally.
286 bool mKeepaliveEnabledPref
{false};
287 // Timeout of pollable event signalling.
288 TimeDuration mPollableEventTimeout
MOZ_GUARDED_BY(mLock
);
290 Atomic
<bool> mServingPendingQueue
{false};
291 Atomic
<int32_t, Relaxed
> mMaxTimePerPollIter
{100};
292 Atomic
<PRIntervalTime
, Relaxed
> mMaxTimeForPrClosePref
;
293 // Timestamp of the last network link change event, tracked
294 // also on child processes.
295 Atomic
<PRIntervalTime
, Relaxed
> mLastNetworkLinkChangeTime
{0};
296 // Preference for how long we do busy wait after network link
297 // change has been detected.
298 Atomic
<PRIntervalTime
, Relaxed
> mNetworkLinkChangeBusyWaitPeriod
;
299 // Preference for the value of timeout for poll() we use during
300 // the network link change event period.
301 Atomic
<PRIntervalTime
, Relaxed
> mNetworkLinkChangeBusyWaitTimeout
;
303 // Between a computer going to sleep and waking up the PR_*** telemetry
304 // will be corrupted - so do not record it.
305 Atomic
<bool, Relaxed
> mSleepPhase
{false};
306 nsCOMPtr
<nsITimer
> mAfterWakeUpTimer
;
308 // Lazily created array of forced port remappings. The tuple members meaning
310 // <0> the greater-or-equal port number of the range to remap
311 // <1> the less-or-equal port number of the range to remap
312 // <2> the port number to remap to, when the given port number falls to the
314 using TPortRemapping
=
315 CopyableTArray
<std::tuple
<uint16_t, uint16_t, uint16_t>>;
316 Maybe
<TPortRemapping
> mPortRemapping
;
318 // Called on the socket thread to apply the mapping build on the main thread
319 // from the preference.
320 void ApplyPortRemapPreference(TPortRemapping
const& portRemapping
);
322 void OnKeepaliveEnabledPrefChange();
323 void NotifyKeepaliveEnabledPrefChange(SocketContext
* sock
);
325 // Report socket status to about:networking
326 void AnalyzeConnection(nsTArray
<SocketInfo
>* data
, SocketContext
* context
,
329 void ClosePrivateConnections();
330 void DetachSocketWithGuard(bool aGuardLocals
, SocketContextList
& socketList
,
333 void MarkTheLastElementOfPendingQueue();
336 Atomic
<bool> mPolling
{false};
337 nsCOMPtr
<nsITimer
> mPollRepairTimer
;
338 void StartPollWatchdog();
344 void TryRepairPollableEvent();
346 CopyableTArray
<nsCOMPtr
<nsISTSShutdownObserver
>> mShutdownObservers
;
349 extern nsSocketTransportService
* gSocketTransportService
;
350 bool OnSocketThread();
353 } // namespace mozilla
355 #endif // !nsSocketTransportService_h__