DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Implementation

Mercurial (d38398e5144e)

VCS Links

LinkedRunnableEvent

SocketContext

nsSocketTransportService

Macros

Line Code
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
/* vim:set ts=4 sw=4 sts=4 ci et: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsSocketTransportService2_h__
#define nsSocketTransportService2_h__

#include "nsPISocketTransportService.h"
#include "nsIThreadInternal.h"
#include "nsIRunnable.h"
#include "nsEventQueue.h"
#include "nsCOMPtr.h"
#include "prinrval.h"
#include "mozilla/Logging.h"
#include "prinit.h"
#include "nsIObserver.h"
#include "mozilla/LinkedList.h"
#include "mozilla/Mutex.h"
#include "mozilla/net/DashboardTypes.h"
#include "mozilla/Atomics.h"
#include "mozilla/TimeStamp.h"
#include "nsITimer.h"
#include "mozilla/UniquePtr.h"
#include "PollableEvent.h"

class nsASocketHandler;
struct PRPollDesc;
class nsIPrefBranch;

//-----------------------------------------------------------------------------

namespace mozilla {
namespace net {

//
// set MOZ_LOG=nsSocketTransport:5
//
extern LazyLogModule gSocketTransportLog;
#define SOCKET_LOG(args)     MOZ_LOG(gSocketTransportLog, LogLevel::Debug, args)
#define SOCKET_LOG_ENABLED() MOZ_LOG_TEST(gSocketTransportLog, LogLevel::Debug)

//
// set MOZ_LOG=UDPSocket:5
//
extern LazyLogModule gUDPSocketLog;
#define UDPSOCKET_LOG(args)     MOZ_LOG(gUDPSocketLog, LogLevel::Debug, args)
#define UDPSOCKET_LOG_ENABLED() MOZ_LOG_TEST(gUDPSocketLog, LogLevel::Debug)

//-----------------------------------------------------------------------------

#define NS_SOCKET_POLL_TIMEOUT PR_INTERVAL_NO_TIMEOUT

//-----------------------------------------------------------------------------

// These maximums are borrowed from the linux kernel.
static const int32_t kMaxTCPKeepIdle  = 32767; // ~9 hours.
static const int32_t kMaxTCPKeepIntvl = 32767;
static const int32_t kMaxTCPKeepCount   = 127;
static const int32_t kDefaultTCPKeepCount =
#if defined (XP_WIN)
                                              10; // Hardcoded in Windows.
#elif defined (XP_MACOSX)
                                              8;  // Hardcoded in OSX.
#else
                                              4;  // Specifiable in Linux.
#endif

class LinkedRunnableEvent final : public LinkedListElement<LinkedRunnableEvent>
{
public:
  explicit LinkedRunnableEvent(nsIRunnable *event) : mEvent(event) {}
  ~LinkedRunnableEvent() {}

  already_AddRefed<nsIRunnable> TakeEvent()
  {
    return mEvent.forget();
  }
private:
    nsCOMPtr<nsIRunnable> mEvent;
};

//-----------------------------------------------------------------------------

class nsSocketTransportService final : public nsPISocketTransportService
                                     , public nsIEventTarget
                                     , public nsIThreadObserver
                                     , public nsIRunnable
                                     , public nsIObserver
{
public:
    NS_DECL_THREADSAFE_ISUPPORTS
    NS_DECL_NSPISOCKETTRANSPORTSERVICE
    NS_DECL_NSISOCKETTRANSPORTSERVICE
    NS_DECL_NSIROUTEDSOCKETTRANSPORTSERVICE
    NS_DECL_NSIEVENTTARGET
    NS_DECL_NSITHREADOBSERVER
    NS_DECL_NSIRUNNABLE
    NS_DECL_NSIOBSERVER 
    using nsIEventTarget::Dispatch;

    nsSocketTransportService();

    // Max Socket count may need to get initialized/used by nsHttpHandler
    // before this class is initialized.
    static uint32_t gMaxCount;
    static PRCallOnceType gMaxCountInitOnce;
    static PRStatus DiscoverMaxCount();

    bool CanAttachSocket();

    // Called by the networking dashboard on the socket thread only
    // Fills the passed array with socket information
    void GetSocketConnections(nsTArray<SocketInfo> *);
    uint64_t GetSentBytes() { return mSentBytesCount; }
    uint64_t GetReceivedBytes() { return mReceivedBytesCount; }

    // Returns true if keepalives are enabled in prefs.
    bool IsKeepaliveEnabled() { return mKeepaliveEnabledPref; }

    bool IsTelemetryEnabledAndNotSleepPhase() { return mTelemetryEnabledPref &&
                                                       !mSleepPhase; }
    PRIntervalTime MaxTimeForPrClosePref() {return mMaxTimeForPrClosePref; }
protected:

    virtual ~nsSocketTransportService();

private:

    //-------------------------------------------------------------------------
    // misc (any thread)
    //-------------------------------------------------------------------------

    nsCOMPtr<nsIThread>      mThread;    // protected by mLock
    UniquePtr<PollableEvent> mPollableEvent;

    // Returns mThread, protecting the get-and-addref with mLock
    already_AddRefed<nsIThread> GetThreadSafely();

    //-------------------------------------------------------------------------
    // initialization and shutdown (any thread)
    //-------------------------------------------------------------------------

    Mutex         mLock;
    bool          mInitialized;
    bool          mShuttingDown;
                            // indicates whether we are currently in the
                            // process of shutting down
    bool          mOffline;
    bool          mGoingOffline;

    // Detaches all sockets.
    void Reset(bool aGuardLocals);

    nsresult ShutdownThread();

    //-------------------------------------------------------------------------
    // socket lists (socket thread only)
    //
    // only "active" sockets are on the poll list.  the active list is kept
    // in sync with the poll list such that:
    //
    //   mActiveList[k].mFD == mPollList[k+1].fd
    //
    // where k=0,1,2,...
    //-------------------------------------------------------------------------

    struct SocketContext
    {
        PRFileDesc       *mFD;
        nsASocketHandler *mHandler;
        uint16_t          mElapsedTime;  // time elapsed w/o activity
    };

    SocketContext *mActiveList;                   /* mListSize entries */
    SocketContext *mIdleList;                     /* mListSize entries */
    nsIThread     *mRawThread;

    uint32_t mActiveListSize;
    uint32_t mIdleListSize;
    uint32_t mActiveCount;
    uint32_t mIdleCount;

    nsresult DetachSocket(SocketContext *, SocketContext *);
    nsresult AddToIdleList(SocketContext *);
    nsresult AddToPollList(SocketContext *);
    void RemoveFromIdleList(SocketContext *);
    void RemoveFromPollList(SocketContext *);
    void MoveToIdleList(SocketContext *sock);
    void MoveToPollList(SocketContext *sock);

    bool GrowActiveList();
    bool GrowIdleList();
    void   InitMaxCount();

    // Total bytes number transfered through all the sockets except active ones
    uint64_t mSentBytesCount;
    uint64_t mReceivedBytesCount;
    //-------------------------------------------------------------------------
    // poll list (socket thread only)
    //
    // first element of the poll list is mPollableEvent (or null if the pollable
    // event cannot be created).
    //-------------------------------------------------------------------------

    PRPollDesc *mPollList;                        /* mListSize + 1 entries */

    PRIntervalTime PollTimeout();            // computes ideal poll timeout
    nsresult       DoPollIteration(TimeDuration *pollDuration);
                                             // perfoms a single poll iteration
    int32_t        Poll(uint32_t *interval,
                        TimeDuration *pollDuration);
                                             // calls PR_Poll.  the out param
                                             // interval indicates the poll
                                             // duration in seconds.
                                             // pollDuration is used only for
                                             // telemetry

    //-------------------------------------------------------------------------
    // pending socket queue - see NotifyWhenCanAttachSocket
    //-------------------------------------------------------------------------
    AutoCleanLinkedList<LinkedRunnableEvent> mPendingSocketQueue;

    // Preference Monitor for SendBufferSize and Keepalive prefs.
    nsresult    UpdatePrefs();
    void        UpdateSendBufferPref(nsIPrefBranch *);
    int32_t     mSendBufferSize;
    // Number of seconds of connection is idle before first keepalive ping.
    int32_t     mKeepaliveIdleTimeS;
    // Number of seconds between retries should keepalive pings fail.
    int32_t     mKeepaliveRetryIntervalS;
    // Number of keepalive probes to send.
    int32_t     mKeepaliveProbeCount;
    // True if TCP keepalive is enabled globally.
    bool        mKeepaliveEnabledPref;

    Atomic<bool>                    mServingPendingQueue;
    Atomic<int32_t, Relaxed>        mMaxTimePerPollIter;
    Atomic<bool, Relaxed>           mTelemetryEnabledPref;
    Atomic<PRIntervalTime, Relaxed> mMaxTimeForPrClosePref;

    // Between a computer going to sleep and waking up the PR_*** telemetry
    // will be corrupted - so do not record it.
    Atomic<bool, Relaxed>           mSleepPhase;
    nsCOMPtr<nsITimer>              mAfterWakeUpTimer;

    void OnKeepaliveEnabledPrefChange();
    void NotifyKeepaliveEnabledPrefChange(SocketContext *sock);

    // Socket thread only for dynamically adjusting max socket size
#if defined(XP_WIN)
    void ProbeMaxCount();
#endif
    bool mProbedMaxCount;

    void AnalyzeConnection(nsTArray<SocketInfo> *data,
                           SocketContext *context, bool aActive);

    void ClosePrivateConnections();
    void DetachSocketWithGuard(bool aGuardLocals,
                               SocketContext *socketList,
                               int32_t index);

    void MarkTheLastElementOfPendingQueue();

#if defined(XP_WIN)
    Atomic<bool> mPolling;
    nsCOMPtr<nsITimer> mPollRepairTimer;
    void StartPollWatchdog();
    void DoPollRepair();
    void StartPolling();
    void EndPolling();
#endif
};

extern nsSocketTransportService *gSocketTransportService;
extern Atomic<PRThread*, Relaxed> gSocketThread;

} // namespace net
} // namespace mozilla

#endif // !nsSocketTransportService_h__