network-monitor.js 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093
  1. /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
  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. "use strict";
  6. const {Cc, Ci, Cm, Cu, Cr, components} = require("chrome");
  7. const Services = require("Services");
  8. const { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm");
  9. loader.lazyRequireGetter(this, "NetworkHelper",
  10. "devtools/shared/webconsole/network-helper");
  11. loader.lazyRequireGetter(this, "DevToolsUtils",
  12. "devtools/shared/DevToolsUtils");
  13. loader.lazyRequireGetter(this, "flags",
  14. "devtools/shared/flags");
  15. loader.lazyRequireGetter(this, "DebuggerServer",
  16. "devtools/server/main", true);
  17. loader.lazyImporter(this, "NetUtil", "resource://gre/modules/NetUtil.jsm");
  18. loader.lazyServiceGetter(this, "gActivityDistributor",
  19. "@mozilla.org/network/http-activity-distributor;1",
  20. "nsIHttpActivityDistributor");
  21. const {NetworkThrottleManager} = require("devtools/shared/webconsole/throttle");
  22. // Network logging
  23. // The maximum uint32 value.
  24. const PR_UINT32_MAX = 4294967295;
  25. // HTTP status codes.
  26. const HTTP_MOVED_PERMANENTLY = 301;
  27. const HTTP_FOUND = 302;
  28. const HTTP_SEE_OTHER = 303;
  29. const HTTP_TEMPORARY_REDIRECT = 307;
  30. // The maximum number of bytes a NetworkResponseListener can hold: 1 MB
  31. const RESPONSE_BODY_LIMIT = 1048576;
  32. // Exported for testing.
  33. exports.RESPONSE_BODY_LIMIT = RESPONSE_BODY_LIMIT;
  34. /**
  35. * Check if a given network request should be logged by a network monitor
  36. * based on the specified filters.
  37. *
  38. * @param nsIHttpChannel channel
  39. * Request to check.
  40. * @param filters
  41. * NetworkMonitor filters to match against.
  42. * @return boolean
  43. * True if the network request should be logged, false otherwise.
  44. */
  45. function matchRequest(channel, filters) {
  46. // Log everything if no filter is specified
  47. if (!filters.outerWindowID && !filters.window && !filters.appId) {
  48. return true;
  49. }
  50. // Ignore requests from chrome or add-on code when we are monitoring
  51. // content.
  52. // TODO: one particular test (browser_styleeditor_fetch-from-cache.js) needs
  53. // the flags.testing check. We will move to a better way to serve
  54. // its needs in bug 1167188, where this check should be removed.
  55. if (!flags.testing && channel.loadInfo &&
  56. channel.loadInfo.loadingDocument === null &&
  57. channel.loadInfo.loadingPrincipal ===
  58. Services.scriptSecurityManager.getSystemPrincipal()) {
  59. return false;
  60. }
  61. if (filters.window) {
  62. // Since frames support, this.window may not be the top level content
  63. // frame, so that we can't only compare with win.top.
  64. let win = NetworkHelper.getWindowForRequest(channel);
  65. while (win) {
  66. if (win == filters.window) {
  67. return true;
  68. }
  69. if (win.parent == win) {
  70. break;
  71. }
  72. win = win.parent;
  73. }
  74. }
  75. if (filters.outerWindowID) {
  76. let topFrame = NetworkHelper.getTopFrameForRequest(channel);
  77. if (topFrame && topFrame.outerWindowID &&
  78. topFrame.outerWindowID == filters.outerWindowID) {
  79. return true;
  80. }
  81. }
  82. if (filters.appId) {
  83. let appId = NetworkHelper.getAppIdForRequest(channel);
  84. if (appId && appId == filters.appId) {
  85. return true;
  86. }
  87. }
  88. return false;
  89. }
  90. /**
  91. * This is a nsIChannelEventSink implementation that monitors channel redirects and
  92. * informs the registered StackTraceCollector about the old and new channels.
  93. */
  94. const SINK_CLASS_DESCRIPTION = "NetworkMonitor Channel Event Sink";
  95. const SINK_CLASS_ID = components.ID("{e89fa076-c845-48a8-8c45-2604729eba1d}");
  96. const SINK_CONTRACT_ID = "@mozilla.org/network/monitor/channeleventsink;1";
  97. const SINK_CATEGORY_NAME = "net-channel-event-sinks";
  98. function ChannelEventSink() {
  99. this.wrappedJSObject = this;
  100. this.collectors = new Set();
  101. }
  102. ChannelEventSink.prototype = {
  103. QueryInterface: XPCOMUtils.generateQI([Ci.nsIChannelEventSink]),
  104. registerCollector(collector) {
  105. this.collectors.add(collector);
  106. },
  107. unregisterCollector(collector) {
  108. this.collectors.delete(collector);
  109. if (this.collectors.size == 0) {
  110. ChannelEventSinkFactory.unregister();
  111. }
  112. },
  113. asyncOnChannelRedirect(oldChannel, newChannel, flags, callback) {
  114. for (let collector of this.collectors) {
  115. try {
  116. collector.onChannelRedirect(oldChannel, newChannel, flags);
  117. } catch (ex) {
  118. console.error("StackTraceCollector.onChannelRedirect threw an exception", ex);
  119. }
  120. }
  121. callback.onRedirectVerifyCallback(Cr.NS_OK);
  122. }
  123. };
  124. const ChannelEventSinkFactory = XPCOMUtils.generateSingletonFactory(ChannelEventSink);
  125. ChannelEventSinkFactory.register = function () {
  126. const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
  127. if (registrar.isCIDRegistered(SINK_CLASS_ID)) {
  128. return;
  129. }
  130. registrar.registerFactory(SINK_CLASS_ID,
  131. SINK_CLASS_DESCRIPTION,
  132. SINK_CONTRACT_ID,
  133. ChannelEventSinkFactory);
  134. XPCOMUtils.categoryManager.addCategoryEntry(SINK_CATEGORY_NAME, SINK_CONTRACT_ID,
  135. SINK_CONTRACT_ID, false, true);
  136. };
  137. ChannelEventSinkFactory.unregister = function () {
  138. const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
  139. registrar.unregisterFactory(SINK_CLASS_ID, ChannelEventSinkFactory);
  140. XPCOMUtils.categoryManager.deleteCategoryEntry(SINK_CATEGORY_NAME, SINK_CONTRACT_ID,
  141. false);
  142. };
  143. ChannelEventSinkFactory.getService = function () {
  144. // Make sure the ChannelEventSink service is registered before accessing it
  145. ChannelEventSinkFactory.register();
  146. return Cc[SINK_CONTRACT_ID].getService(Ci.nsIChannelEventSink).wrappedJSObject;
  147. };
  148. function StackTraceCollector(filters) {
  149. this.filters = filters;
  150. this.stacktracesById = new Map();
  151. }
  152. StackTraceCollector.prototype = {
  153. init() {
  154. Services.obs.addObserver(this, "http-on-opening-request", false);
  155. ChannelEventSinkFactory.getService().registerCollector(this);
  156. },
  157. destroy() {
  158. Services.obs.removeObserver(this, "http-on-opening-request");
  159. ChannelEventSinkFactory.getService().unregisterCollector(this);
  160. },
  161. _saveStackTrace(channel, stacktrace) {
  162. this.stacktracesById.set(channel.channelId, stacktrace);
  163. },
  164. observe(subject) {
  165. let channel = subject.QueryInterface(Ci.nsIHttpChannel);
  166. if (!matchRequest(channel, this.filters)) {
  167. return;
  168. }
  169. // Convert the nsIStackFrame XPCOM objects to a nice JSON that can be
  170. // passed around through message managers etc.
  171. let frame = components.stack;
  172. let stacktrace = [];
  173. if (frame && frame.caller) {
  174. frame = frame.caller;
  175. while (frame) {
  176. stacktrace.push({
  177. filename: frame.filename,
  178. lineNumber: frame.lineNumber,
  179. columnNumber: frame.columnNumber,
  180. functionName: frame.name,
  181. asyncCause: frame.asyncCause,
  182. });
  183. frame = frame.caller || frame.asyncCaller;
  184. }
  185. }
  186. this._saveStackTrace(channel, stacktrace);
  187. },
  188. onChannelRedirect(oldChannel, newChannel, flags) {
  189. // We can be called with any nsIChannel, but are interested only in HTTP channels
  190. try {
  191. oldChannel.QueryInterface(Ci.nsIHttpChannel);
  192. newChannel.QueryInterface(Ci.nsIHttpChannel);
  193. } catch (ex) {
  194. return;
  195. }
  196. let oldId = oldChannel.channelId;
  197. let stacktrace = this.stacktracesById.get(oldId);
  198. if (stacktrace) {
  199. this.stacktracesById.delete(oldId);
  200. this._saveStackTrace(newChannel, stacktrace);
  201. }
  202. },
  203. getStackTrace(channelId) {
  204. let trace = this.stacktracesById.get(channelId);
  205. this.stacktracesById.delete(channelId);
  206. return trace;
  207. }
  208. };
  209. exports.StackTraceCollector = StackTraceCollector;
  210. /**
  211. * The network response listener implements the nsIStreamListener and
  212. * nsIRequestObserver interfaces. This is used within the NetworkMonitor feature
  213. * to get the response body of the request.
  214. *
  215. * The code is mostly based on code listings from:
  216. *
  217. * http://www.softwareishard.com/blog/firebug/
  218. * nsitraceablechannel-intercept-http-traffic/
  219. *
  220. * @constructor
  221. * @param object owner
  222. * The response listener owner. This object needs to hold the
  223. * |openResponses| object.
  224. * @param object httpActivity
  225. * HttpActivity object associated with this request. See NetworkMonitor
  226. * for more information.
  227. */
  228. function NetworkResponseListener(owner, httpActivity) {
  229. this.owner = owner;
  230. this.receivedData = "";
  231. this.httpActivity = httpActivity;
  232. this.bodySize = 0;
  233. // Note that this is really only needed for the non-e10s case.
  234. // See bug 1309523.
  235. let channel = this.httpActivity.channel;
  236. this._wrappedNotificationCallbacks = channel.notificationCallbacks;
  237. channel.notificationCallbacks = this;
  238. }
  239. NetworkResponseListener.prototype = {
  240. QueryInterface:
  241. XPCOMUtils.generateQI([Ci.nsIStreamListener, Ci.nsIInputStreamCallback,
  242. Ci.nsIRequestObserver, Ci.nsIInterfaceRequestor,
  243. Ci.nsISupports]),
  244. // nsIInterfaceRequestor implementation
  245. /**
  246. * This object implements nsIProgressEventSink, but also needs to forward
  247. * interface requests to the notification callbacks of other objects.
  248. */
  249. getInterface(iid) {
  250. if (iid.equals(Ci.nsIProgressEventSink)) {
  251. return this;
  252. }
  253. if (this._wrappedNotificationCallbacks) {
  254. return this._wrappedNotificationCallbacks.getInterface(iid);
  255. }
  256. throw Cr.NS_ERROR_NO_INTERFACE;
  257. },
  258. /**
  259. * Forward notifications for interfaces this object implements, in case other
  260. * objects also implemented them.
  261. */
  262. _forwardNotification(iid, method, args) {
  263. if (!this._wrappedNotificationCallbacks) {
  264. return;
  265. }
  266. try {
  267. let impl = this._wrappedNotificationCallbacks.getInterface(iid);
  268. impl[method].apply(impl, args);
  269. } catch (e) {
  270. if (e.result != Cr.NS_ERROR_NO_INTERFACE) {
  271. throw e;
  272. }
  273. }
  274. },
  275. /**
  276. * This NetworkResponseListener tracks the NetworkMonitor.openResponses object
  277. * to find the associated uncached headers.
  278. * @private
  279. */
  280. _foundOpenResponse: false,
  281. /**
  282. * If the channel already had notificationCallbacks, hold them here internally
  283. * so that we can forward getInterface requests to that object.
  284. */
  285. _wrappedNotificationCallbacks: null,
  286. /**
  287. * The response listener owner.
  288. */
  289. owner: null,
  290. /**
  291. * The response will be written into the outputStream of this nsIPipe.
  292. * Both ends of the pipe must be blocking.
  293. */
  294. sink: null,
  295. /**
  296. * The HttpActivity object associated with this response.
  297. */
  298. httpActivity: null,
  299. /**
  300. * Stores the received data as a string.
  301. */
  302. receivedData: null,
  303. /**
  304. * The uncompressed, decoded response body size.
  305. */
  306. bodySize: null,
  307. /**
  308. * Response body size on the wire, potentially compressed / encoded.
  309. */
  310. transferredSize: null,
  311. /**
  312. * The nsIRequest we are started for.
  313. */
  314. request: null,
  315. /**
  316. * Set the async listener for the given nsIAsyncInputStream. This allows us to
  317. * wait asynchronously for any data coming from the stream.
  318. *
  319. * @param nsIAsyncInputStream stream
  320. * The input stream from where we are waiting for data to come in.
  321. * @param nsIInputStreamCallback listener
  322. * The input stream callback you want. This is an object that must have
  323. * the onInputStreamReady() method. If the argument is null, then the
  324. * current callback is removed.
  325. * @return void
  326. */
  327. setAsyncListener: function (stream, listener) {
  328. // Asynchronously wait for the stream to be readable or closed.
  329. stream.asyncWait(listener, 0, 0, Services.tm.mainThread);
  330. },
  331. /**
  332. * Stores the received data, if request/response body logging is enabled. It
  333. * also does limit the number of stored bytes, based on the
  334. * RESPONSE_BODY_LIMIT constant.
  335. *
  336. * Learn more about nsIStreamListener at:
  337. * https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIStreamListener
  338. *
  339. * @param nsIRequest request
  340. * @param nsISupports context
  341. * @param nsIInputStream inputStream
  342. * @param unsigned long offset
  343. * @param unsigned long count
  344. */
  345. onDataAvailable: function (request, context, inputStream, offset, count) {
  346. this._findOpenResponse();
  347. let data = NetUtil.readInputStreamToString(inputStream, count);
  348. this.bodySize += count;
  349. if (!this.httpActivity.discardResponseBody &&
  350. this.receivedData.length < RESPONSE_BODY_LIMIT) {
  351. this.receivedData +=
  352. NetworkHelper.convertToUnicode(data, request.contentCharset);
  353. }
  354. },
  355. /**
  356. * See documentation at
  357. * https://developer.mozilla.org/En/NsIRequestObserver
  358. *
  359. * @param nsIRequest request
  360. * @param nsISupports context
  361. */
  362. onStartRequest: function (request) {
  363. // Converter will call this again, we should just ignore that.
  364. if (this.request) {
  365. return;
  366. }
  367. this.request = request;
  368. this._getSecurityInfo();
  369. this._findOpenResponse();
  370. // We need to track the offset for the onDataAvailable calls where
  371. // we pass the data from our pipe to the converter.
  372. this.offset = 0;
  373. // In the multi-process mode, the conversion happens on the child
  374. // side while we can only monitor the channel on the parent
  375. // side. If the content is gzipped, we have to unzip it
  376. // ourself. For that we use the stream converter services. Do not
  377. // do that for Service workers as they are run in the child
  378. // process.
  379. let channel = this.request;
  380. if (!this.httpActivity.fromServiceWorker &&
  381. channel instanceof Ci.nsIEncodedChannel &&
  382. channel.contentEncodings &&
  383. !channel.applyConversion) {
  384. let encodingHeader = channel.getResponseHeader("Content-Encoding");
  385. let scs = Cc["@mozilla.org/streamConverters;1"]
  386. .getService(Ci.nsIStreamConverterService);
  387. let encodings = encodingHeader.split(/\s*\t*,\s*\t*/);
  388. let nextListener = this;
  389. let acceptedEncodings = ["gzip", "deflate", "br", "x-gzip", "x-deflate"];
  390. for (let i in encodings) {
  391. // There can be multiple conversions applied
  392. let enc = encodings[i].toLowerCase();
  393. if (acceptedEncodings.indexOf(enc) > -1) {
  394. this.converter = scs.asyncConvertData(enc, "uncompressed",
  395. nextListener, null);
  396. nextListener = this.converter;
  397. }
  398. }
  399. if (this.converter) {
  400. this.converter.onStartRequest(this.request, null);
  401. }
  402. }
  403. // Asynchronously wait for the data coming from the request.
  404. this.setAsyncListener(this.sink.inputStream, this);
  405. },
  406. /**
  407. * Parse security state of this request and report it to the client.
  408. */
  409. _getSecurityInfo: DevToolsUtils.makeInfallible(function () {
  410. // Many properties of the securityInfo (e.g., the server certificate or HPKP
  411. // status) are not available in the content process and can't be even touched safely,
  412. // because their C++ getters trigger assertions. This function is called in content
  413. // process for synthesized responses from service workers, in the parent otherwise.
  414. if (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT) {
  415. return;
  416. }
  417. // Take the security information from the original nsIHTTPChannel instead of
  418. // the nsIRequest received in onStartRequest. If response to this request
  419. // was a redirect from http to https, the request object seems to contain
  420. // security info for the https request after redirect.
  421. let secinfo = this.httpActivity.channel.securityInfo;
  422. let info = NetworkHelper.parseSecurityInfo(secinfo, this.httpActivity);
  423. this.httpActivity.owner.addSecurityInfo(info);
  424. }),
  425. /**
  426. * Handle the onStopRequest by closing the sink output stream.
  427. *
  428. * For more documentation about nsIRequestObserver go to:
  429. * https://developer.mozilla.org/En/NsIRequestObserver
  430. */
  431. onStopRequest: function () {
  432. this._findOpenResponse();
  433. this.sink.outputStream.close();
  434. },
  435. // nsIProgressEventSink implementation
  436. /**
  437. * Handle progress event as data is transferred. This is used to record the
  438. * size on the wire, which may be compressed / encoded.
  439. */
  440. onProgress: function (request, context, progress, progressMax) {
  441. this.transferredSize = progress;
  442. // Need to forward as well to keep things like Download Manager's progress
  443. // bar working properly.
  444. this._forwardNotification(Ci.nsIProgressEventSink, "onProgress", arguments);
  445. },
  446. onStatus: function () {
  447. this._forwardNotification(Ci.nsIProgressEventSink, "onStatus", arguments);
  448. },
  449. /**
  450. * Find the open response object associated to the current request. The
  451. * NetworkMonitor._httpResponseExaminer() method saves the response headers in
  452. * NetworkMonitor.openResponses. This method takes the data from the open
  453. * response object and puts it into the HTTP activity object, then sends it to
  454. * the remote Web Console instance.
  455. *
  456. * @private
  457. */
  458. _findOpenResponse: function () {
  459. if (!this.owner || this._foundOpenResponse) {
  460. return;
  461. }
  462. let openResponse = null;
  463. for (let id in this.owner.openResponses) {
  464. let item = this.owner.openResponses[id];
  465. if (item.channel === this.httpActivity.channel) {
  466. openResponse = item;
  467. break;
  468. }
  469. }
  470. if (!openResponse) {
  471. return;
  472. }
  473. this._foundOpenResponse = true;
  474. delete this.owner.openResponses[openResponse.id];
  475. this.httpActivity.owner.addResponseHeaders(openResponse.headers);
  476. this.httpActivity.owner.addResponseCookies(openResponse.cookies);
  477. },
  478. /**
  479. * Clean up the response listener once the response input stream is closed.
  480. * This is called from onStopRequest() or from onInputStreamReady() when the
  481. * stream is closed.
  482. * @return void
  483. */
  484. onStreamClose: function () {
  485. if (!this.httpActivity) {
  486. return;
  487. }
  488. // Remove our listener from the request input stream.
  489. this.setAsyncListener(this.sink.inputStream, null);
  490. this._findOpenResponse();
  491. if (!this.httpActivity.discardResponseBody && this.receivedData.length) {
  492. this._onComplete(this.receivedData);
  493. } else if (!this.httpActivity.discardResponseBody &&
  494. this.httpActivity.responseStatus == 304) {
  495. // Response is cached, so we load it from cache.
  496. let charset = this.request.contentCharset || this.httpActivity.charset;
  497. NetworkHelper.loadFromCache(this.httpActivity.url, charset,
  498. this._onComplete.bind(this));
  499. } else {
  500. this._onComplete();
  501. }
  502. },
  503. /**
  504. * Handler for when the response completes. This function cleans up the
  505. * response listener.
  506. *
  507. * @param string [data]
  508. * Optional, the received data coming from the response listener or
  509. * from the cache.
  510. */
  511. _onComplete: function (data) {
  512. let response = {
  513. mimeType: "",
  514. text: data || "",
  515. };
  516. response.size = this.bodySize;
  517. response.transferredSize = this.transferredSize;
  518. try {
  519. response.mimeType = this.request.contentType;
  520. } catch (ex) {
  521. // Ignore.
  522. }
  523. if (!response.mimeType ||
  524. !NetworkHelper.isTextMimeType(response.mimeType)) {
  525. response.encoding = "base64";
  526. try {
  527. response.text = btoa(response.text);
  528. } catch (err) {
  529. // Ignore.
  530. }
  531. }
  532. if (response.mimeType && this.request.contentCharset) {
  533. response.mimeType += "; charset=" + this.request.contentCharset;
  534. }
  535. this.receivedData = "";
  536. this.httpActivity.owner.addResponseContent(
  537. response,
  538. this.httpActivity.discardResponseBody
  539. );
  540. this._wrappedNotificationCallbacks = null;
  541. this.httpActivity = null;
  542. this.sink = null;
  543. this.inputStream = null;
  544. this.converter = null;
  545. this.request = null;
  546. this.owner = null;
  547. },
  548. /**
  549. * The nsIInputStreamCallback for when the request input stream is ready -
  550. * either it has more data or it is closed.
  551. *
  552. * @param nsIAsyncInputStream stream
  553. * The sink input stream from which data is coming.
  554. * @returns void
  555. */
  556. onInputStreamReady: function (stream) {
  557. if (!(stream instanceof Ci.nsIAsyncInputStream) || !this.httpActivity) {
  558. return;
  559. }
  560. let available = -1;
  561. try {
  562. // This may throw if the stream is closed normally or due to an error.
  563. available = stream.available();
  564. } catch (ex) {
  565. // Ignore.
  566. }
  567. if (available != -1) {
  568. if (available != 0) {
  569. if (this.converter) {
  570. this.converter.onDataAvailable(this.request, null, stream,
  571. this.offset, available);
  572. } else {
  573. this.onDataAvailable(this.request, null, stream, this.offset,
  574. available);
  575. }
  576. }
  577. this.offset += available;
  578. this.setAsyncListener(stream, this);
  579. } else {
  580. this.onStreamClose();
  581. this.offset = 0;
  582. }
  583. },
  584. };
  585. /**
  586. * The network monitor uses the nsIHttpActivityDistributor to monitor network
  587. * requests. The nsIObserverService is also used for monitoring
  588. * http-on-examine-response notifications. All network request information is
  589. * routed to the remote Web Console.
  590. *
  591. * @constructor
  592. * @param object filters
  593. * Object with the filters to use for network requests:
  594. * - window (nsIDOMWindow): filter network requests by the associated
  595. * window object.
  596. * - appId (number): filter requests by the appId.
  597. * - outerWindowID (number): filter requests by their top frame's outerWindowID.
  598. * Filters are optional. If any of these filters match the request is
  599. * logged (OR is applied). If no filter is provided then all requests are
  600. * logged.
  601. * @param object owner
  602. * The network monitor owner. This object needs to hold:
  603. * - onNetworkEvent(requestInfo)
  604. * This method is invoked once for every new network request and it is
  605. * given the initial network request information as an argument.
  606. * onNetworkEvent() must return an object which holds several add*()
  607. * methods which are used to add further network request/response information.
  608. * - stackTraceCollector
  609. * If the owner has this optional property, it will be used as a
  610. * StackTraceCollector by the NetworkMonitor.
  611. */
  612. function NetworkMonitor(filters, owner) {
  613. this.filters = filters;
  614. this.owner = owner;
  615. this.openRequests = {};
  616. this.openResponses = {};
  617. this._httpResponseExaminer =
  618. DevToolsUtils.makeInfallible(this._httpResponseExaminer).bind(this);
  619. this._httpModifyExaminer =
  620. DevToolsUtils.makeInfallible(this._httpModifyExaminer).bind(this);
  621. this._serviceWorkerRequest = this._serviceWorkerRequest.bind(this);
  622. this._throttleData = null;
  623. this._throttler = null;
  624. }
  625. exports.NetworkMonitor = NetworkMonitor;
  626. NetworkMonitor.prototype = {
  627. filters: null,
  628. httpTransactionCodes: {
  629. 0x5001: "REQUEST_HEADER",
  630. 0x5002: "REQUEST_BODY_SENT",
  631. 0x5003: "RESPONSE_START",
  632. 0x5004: "RESPONSE_HEADER",
  633. 0x5005: "RESPONSE_COMPLETE",
  634. 0x5006: "TRANSACTION_CLOSE",
  635. 0x804b0003: "STATUS_RESOLVING",
  636. 0x804b000b: "STATUS_RESOLVED",
  637. 0x804b0007: "STATUS_CONNECTING_TO",
  638. 0x804b0004: "STATUS_CONNECTED_TO",
  639. 0x804b0005: "STATUS_SENDING_TO",
  640. 0x804b000a: "STATUS_WAITING_FOR",
  641. 0x804b0006: "STATUS_RECEIVING_FROM",
  642. 0x804b000c: "STATUS_TLS_STARTING",
  643. 0x804b000d: "STATUS_TLS_ENDING"
  644. },
  645. httpDownloadActivities: [
  646. gActivityDistributor.ACTIVITY_SUBTYPE_RESPONSE_START,
  647. gActivityDistributor.ACTIVITY_SUBTYPE_RESPONSE_HEADER,
  648. gActivityDistributor.ACTIVITY_SUBTYPE_RESPONSE_COMPLETE,
  649. gActivityDistributor.ACTIVITY_SUBTYPE_TRANSACTION_CLOSE
  650. ],
  651. // Network response bodies are piped through a buffer of the given size (in
  652. // bytes).
  653. responsePipeSegmentSize: null,
  654. owner: null,
  655. /**
  656. * Whether to save the bodies of network requests and responses.
  657. * @type boolean
  658. */
  659. saveRequestAndResponseBodies: true,
  660. /**
  661. * Object that holds the HTTP activity objects for ongoing requests.
  662. */
  663. openRequests: null,
  664. /**
  665. * Object that holds response headers coming from this._httpResponseExaminer.
  666. */
  667. openResponses: null,
  668. /**
  669. * The network monitor initializer.
  670. */
  671. init: function () {
  672. this.responsePipeSegmentSize = Services.prefs
  673. .getIntPref("network.buffer.cache.size");
  674. this.interceptedChannels = new Set();
  675. if (Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT) {
  676. gActivityDistributor.addObserver(this);
  677. Services.obs.addObserver(this._httpResponseExaminer,
  678. "http-on-examine-response", false);
  679. Services.obs.addObserver(this._httpResponseExaminer,
  680. "http-on-examine-cached-response", false);
  681. Services.obs.addObserver(this._httpModifyExaminer,
  682. "http-on-modify-request", false);
  683. }
  684. // In child processes, only watch for service worker requests
  685. // everything else only happens in the parent process
  686. Services.obs.addObserver(this._serviceWorkerRequest,
  687. "service-worker-synthesized-response", false);
  688. },
  689. get throttleData() {
  690. return this._throttleData;
  691. },
  692. set throttleData(value) {
  693. this._throttleData = value;
  694. // Clear out any existing throttlers
  695. this._throttler = null;
  696. },
  697. _getThrottler: function () {
  698. if (this.throttleData !== null && this._throttler === null) {
  699. this._throttler = new NetworkThrottleManager(this.throttleData);
  700. }
  701. return this._throttler;
  702. },
  703. _serviceWorkerRequest: function (subject, topic, data) {
  704. let channel = subject.QueryInterface(Ci.nsIHttpChannel);
  705. if (!matchRequest(channel, this.filters)) {
  706. return;
  707. }
  708. this.interceptedChannels.add(subject);
  709. // On e10s, we never receive http-on-examine-cached-response, so fake one.
  710. if (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT) {
  711. this._httpResponseExaminer(channel, "http-on-examine-cached-response");
  712. }
  713. },
  714. /**
  715. * Observe notifications for the http-on-examine-response topic, coming from
  716. * the nsIObserverService.
  717. *
  718. * @private
  719. * @param nsIHttpChannel subject
  720. * @param string topic
  721. * @returns void
  722. */
  723. _httpResponseExaminer: function (subject, topic) {
  724. // The httpResponseExaminer is used to retrieve the uncached response
  725. // headers. The data retrieved is stored in openResponses. The
  726. // NetworkResponseListener is responsible with updating the httpActivity
  727. // object with the data from the new object in openResponses.
  728. if (!this.owner ||
  729. (topic != "http-on-examine-response" &&
  730. topic != "http-on-examine-cached-response") ||
  731. !(subject instanceof Ci.nsIHttpChannel)) {
  732. return;
  733. }
  734. let channel = subject.QueryInterface(Ci.nsIHttpChannel);
  735. if (!matchRequest(channel, this.filters)) {
  736. return;
  737. }
  738. let response = {
  739. id: gSequenceId(),
  740. channel: channel,
  741. headers: [],
  742. cookies: [],
  743. };
  744. let setCookieHeader = null;
  745. channel.visitResponseHeaders({
  746. visitHeader: function (name, value) {
  747. let lowerName = name.toLowerCase();
  748. if (lowerName == "set-cookie") {
  749. setCookieHeader = value;
  750. }
  751. response.headers.push({ name: name, value: value });
  752. }
  753. });
  754. if (!response.headers.length) {
  755. // No need to continue.
  756. return;
  757. }
  758. if (setCookieHeader) {
  759. response.cookies = NetworkHelper.parseSetCookieHeader(setCookieHeader);
  760. }
  761. // Determine the HTTP version.
  762. let httpVersionMaj = {};
  763. let httpVersionMin = {};
  764. channel.QueryInterface(Ci.nsIHttpChannelInternal);
  765. channel.getResponseVersion(httpVersionMaj, httpVersionMin);
  766. response.status = channel.responseStatus;
  767. response.statusText = channel.responseStatusText;
  768. response.httpVersion = "HTTP/" + httpVersionMaj.value + "." +
  769. httpVersionMin.value;
  770. this.openResponses[response.id] = response;
  771. if (topic === "http-on-examine-cached-response") {
  772. // Service worker requests emits cached-reponse notification on non-e10s,
  773. // and we fake one on e10s.
  774. let fromServiceWorker = this.interceptedChannels.has(channel);
  775. this.interceptedChannels.delete(channel);
  776. // If this is a cached response, there never was a request event
  777. // so we need to construct one here so the frontend gets all the
  778. // expected events.
  779. let httpActivity = this._createNetworkEvent(channel, {
  780. fromCache: !fromServiceWorker,
  781. fromServiceWorker: fromServiceWorker
  782. });
  783. httpActivity.owner.addResponseStart({
  784. httpVersion: response.httpVersion,
  785. remoteAddress: "",
  786. remotePort: "",
  787. status: response.status,
  788. statusText: response.statusText,
  789. headersSize: 0,
  790. }, "", true);
  791. // There also is never any timing events, so we can fire this
  792. // event with zeroed out values.
  793. let timings = this._setupHarTimings(httpActivity, true);
  794. httpActivity.owner.addEventTimings(timings.total, timings.timings);
  795. }
  796. },
  797. /**
  798. * Observe notifications for the http-on-modify-request topic, coming from
  799. * the nsIObserverService.
  800. *
  801. * @private
  802. * @param nsIHttpChannel aSubject
  803. * @returns void
  804. */
  805. _httpModifyExaminer: function (subject) {
  806. let throttler = this._getThrottler();
  807. if (throttler) {
  808. let channel = subject.QueryInterface(Ci.nsIHttpChannel);
  809. if (matchRequest(channel, this.filters)) {
  810. // Read any request body here, before it is throttled.
  811. let httpActivity = this.createOrGetActivityObject(channel);
  812. this._onRequestBodySent(httpActivity);
  813. throttler.manageUpload(channel);
  814. }
  815. }
  816. },
  817. /**
  818. * A helper function for observeActivity. This does whatever work
  819. * is required by a particular http activity event. Arguments are
  820. * the same as for observeActivity.
  821. */
  822. _dispatchActivity: function (httpActivity, channel, activityType,
  823. activitySubtype, timestamp, extraSizeData,
  824. extraStringData) {
  825. let transCodes = this.httpTransactionCodes;
  826. // Store the time information for this activity subtype.
  827. if (activitySubtype in transCodes) {
  828. let stage = transCodes[activitySubtype];
  829. if (stage in httpActivity.timings) {
  830. httpActivity.timings[stage].last = timestamp;
  831. } else {
  832. httpActivity.timings[stage] = {
  833. first: timestamp,
  834. last: timestamp,
  835. };
  836. }
  837. }
  838. switch (activitySubtype) {
  839. case gActivityDistributor.ACTIVITY_SUBTYPE_REQUEST_BODY_SENT:
  840. this._onRequestBodySent(httpActivity);
  841. if (httpActivity.sentBody !== null) {
  842. httpActivity.owner.addRequestPostData({ text: httpActivity.sentBody });
  843. httpActivity.sentBody = null;
  844. }
  845. break;
  846. case gActivityDistributor.ACTIVITY_SUBTYPE_RESPONSE_HEADER:
  847. this._onResponseHeader(httpActivity, extraStringData);
  848. break;
  849. case gActivityDistributor.ACTIVITY_SUBTYPE_TRANSACTION_CLOSE:
  850. this._onTransactionClose(httpActivity);
  851. break;
  852. default:
  853. break;
  854. }
  855. },
  856. /**
  857. * Begin observing HTTP traffic that originates inside the current tab.
  858. *
  859. * @see https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIHttpActivityObserver
  860. *
  861. * @param nsIHttpChannel channel
  862. * @param number activityType
  863. * @param number activitySubtype
  864. * @param number timestamp
  865. * @param number extraSizeData
  866. * @param string extraStringData
  867. */
  868. observeActivity:
  869. DevToolsUtils.makeInfallible(function (channel, activityType, activitySubtype,
  870. timestamp, extraSizeData,
  871. extraStringData) {
  872. if (!this.owner ||
  873. activityType != gActivityDistributor.ACTIVITY_TYPE_HTTP_TRANSACTION &&
  874. activityType != gActivityDistributor.ACTIVITY_TYPE_SOCKET_TRANSPORT) {
  875. return;
  876. }
  877. if (!(channel instanceof Ci.nsIHttpChannel)) {
  878. return;
  879. }
  880. channel = channel.QueryInterface(Ci.nsIHttpChannel);
  881. if (activitySubtype ==
  882. gActivityDistributor.ACTIVITY_SUBTYPE_REQUEST_HEADER) {
  883. this._onRequestHeader(channel, timestamp, extraStringData);
  884. return;
  885. }
  886. // Iterate over all currently ongoing requests. If channel can't
  887. // be found within them, then exit this function.
  888. let httpActivity = this._findActivityObject(channel);
  889. if (!httpActivity) {
  890. return;
  891. }
  892. // If we're throttling, we must not report events as they arrive
  893. // from platform, but instead let the throttler emit the events
  894. // after some time has elapsed.
  895. if (httpActivity.downloadThrottle &&
  896. this.httpDownloadActivities.indexOf(activitySubtype) >= 0) {
  897. let callback = this._dispatchActivity.bind(this);
  898. httpActivity.downloadThrottle
  899. .addActivityCallback(callback, httpActivity, channel, activityType,
  900. activitySubtype, timestamp, extraSizeData,
  901. extraStringData);
  902. } else {
  903. this._dispatchActivity(httpActivity, channel, activityType,
  904. activitySubtype, timestamp, extraSizeData,
  905. extraStringData);
  906. }
  907. }),
  908. /**
  909. *
  910. */
  911. _createNetworkEvent: function (channel, { timestamp, extraStringData,
  912. fromCache, fromServiceWorker }) {
  913. let httpActivity = this.createOrGetActivityObject(channel);
  914. channel.QueryInterface(Ci.nsIPrivateBrowsingChannel);
  915. httpActivity.private = channel.isChannelPrivate;
  916. if (timestamp) {
  917. httpActivity.timings.REQUEST_HEADER = {
  918. first: timestamp,
  919. last: timestamp
  920. };
  921. }
  922. let event = {};
  923. event.method = channel.requestMethod;
  924. event.channelId = channel.channelId;
  925. event.url = channel.URI.spec;
  926. event.private = httpActivity.private;
  927. event.headersSize = 0;
  928. event.startedDateTime =
  929. (timestamp ? new Date(Math.round(timestamp / 1000)) : new Date())
  930. .toISOString();
  931. event.fromCache = fromCache;
  932. event.fromServiceWorker = fromServiceWorker;
  933. httpActivity.fromServiceWorker = fromServiceWorker;
  934. if (extraStringData) {
  935. event.headersSize = extraStringData.length;
  936. }
  937. // Determine the cause and if this is an XHR request.
  938. let causeType = channel.loadInfo.externalContentPolicyType;
  939. let loadingPrincipal = channel.loadInfo.loadingPrincipal;
  940. let causeUri = loadingPrincipal ? loadingPrincipal.URI : null;
  941. let stacktrace;
  942. // If this is the parent process, there is no stackTraceCollector - the stack
  943. // trace will be added in NetworkMonitorChild._onNewEvent.
  944. if (this.owner.stackTraceCollector) {
  945. stacktrace = this.owner.stackTraceCollector.getStackTrace(event.channelId);
  946. }
  947. event.cause = {
  948. type: causeType,
  949. loadingDocumentUri: causeUri ? causeUri.spec : null,
  950. stacktrace
  951. };
  952. httpActivity.isXHR = event.isXHR =
  953. (causeType === Ci.nsIContentPolicy.TYPE_XMLHTTPREQUEST ||
  954. causeType === Ci.nsIContentPolicy.TYPE_FETCH);
  955. // Determine the HTTP version.
  956. let httpVersionMaj = {};
  957. let httpVersionMin = {};
  958. channel.QueryInterface(Ci.nsIHttpChannelInternal);
  959. channel.getRequestVersion(httpVersionMaj, httpVersionMin);
  960. event.httpVersion = "HTTP/" + httpVersionMaj.value + "." +
  961. httpVersionMin.value;
  962. event.discardRequestBody = !this.saveRequestAndResponseBodies;
  963. event.discardResponseBody = !this.saveRequestAndResponseBodies;
  964. let headers = [];
  965. let cookies = [];
  966. let cookieHeader = null;
  967. // Copy the request header data.
  968. channel.visitRequestHeaders({
  969. visitHeader: function (name, value) {
  970. if (name == "Cookie") {
  971. cookieHeader = value;
  972. }
  973. headers.push({ name: name, value: value });
  974. }
  975. });
  976. if (cookieHeader) {
  977. cookies = NetworkHelper.parseCookieHeader(cookieHeader);
  978. }
  979. httpActivity.owner = this.owner.onNetworkEvent(event);
  980. this._setupResponseListener(httpActivity, fromCache);
  981. httpActivity.owner.addRequestHeaders(headers, extraStringData);
  982. httpActivity.owner.addRequestCookies(cookies);
  983. return httpActivity;
  984. },
  985. /**
  986. * Handler for ACTIVITY_SUBTYPE_REQUEST_HEADER. When a request starts the
  987. * headers are sent to the server. This method creates the |httpActivity|
  988. * object where we store the request and response information that is
  989. * collected through its lifetime.
  990. *
  991. * @private
  992. * @param nsIHttpChannel channel
  993. * @param number timestamp
  994. * @param string extraStringData
  995. * @return void
  996. */
  997. _onRequestHeader: function (channel, timestamp, extraStringData) {
  998. if (!matchRequest(channel, this.filters)) {
  999. return;
  1000. }
  1001. this._createNetworkEvent(channel, { timestamp, extraStringData });
  1002. },
  1003. /**
  1004. * Find an HTTP activity object for the channel.
  1005. *
  1006. * @param nsIHttpChannel channel
  1007. * The HTTP channel whose activity object we want to find.
  1008. * @return object
  1009. * The HTTP activity object, or null if it is not found.
  1010. */
  1011. _findActivityObject: function (channel) {
  1012. for (let id in this.openRequests) {
  1013. let item = this.openRequests[id];
  1014. if (item.channel === channel) {
  1015. return item;
  1016. }
  1017. }
  1018. return null;
  1019. },
  1020. /**
  1021. * Find an existing HTTP activity object, or create a new one. This
  1022. * object is used for storing all the request and response
  1023. * information.
  1024. *
  1025. * This is a HAR-like object. Conformance to the spec is not guaranteed at
  1026. * this point.
  1027. *
  1028. * @see http://www.softwareishard.com/blog/har-12-spec
  1029. * @param nsIHttpChannel channel
  1030. * The HTTP channel for which the HTTP activity object is created.
  1031. * @return object
  1032. * The new HTTP activity object.
  1033. */
  1034. createOrGetActivityObject: function (channel) {
  1035. let httpActivity = this._findActivityObject(channel);
  1036. if (!httpActivity) {
  1037. let win = NetworkHelper.getWindowForRequest(channel);
  1038. let charset = win ? win.document.characterSet : null;
  1039. httpActivity = {
  1040. id: gSequenceId(),
  1041. channel: channel,
  1042. // see _onRequestBodySent()
  1043. charset: charset,
  1044. sentBody: null,
  1045. url: channel.URI.spec,
  1046. // needed for host specific security info
  1047. hostname: channel.URI.host,
  1048. discardRequestBody: !this.saveRequestAndResponseBodies,
  1049. discardResponseBody: !this.saveRequestAndResponseBodies,
  1050. // internal timing information, see observeActivity()
  1051. timings: {},
  1052. // see _onResponseHeader()
  1053. responseStatus: null,
  1054. // the activity owner which is notified when changes happen
  1055. owner: null,
  1056. };
  1057. this.openRequests[httpActivity.id] = httpActivity;
  1058. }
  1059. return httpActivity;
  1060. },
  1061. /**
  1062. * Setup the network response listener for the given HTTP activity. The
  1063. * NetworkResponseListener is responsible for storing the response body.
  1064. *
  1065. * @private
  1066. * @param object httpActivity
  1067. * The HTTP activity object we are tracking.
  1068. */
  1069. _setupResponseListener: function (httpActivity, fromCache) {
  1070. let channel = httpActivity.channel;
  1071. channel.QueryInterface(Ci.nsITraceableChannel);
  1072. if (!fromCache) {
  1073. let throttler = this._getThrottler();
  1074. if (throttler) {
  1075. httpActivity.downloadThrottle = throttler.manage(channel);
  1076. }
  1077. }
  1078. // The response will be written into the outputStream of this pipe.
  1079. // This allows us to buffer the data we are receiving and read it
  1080. // asynchronously.
  1081. // Both ends of the pipe must be blocking.
  1082. let sink = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe);
  1083. // The streams need to be blocking because this is required by the
  1084. // stream tee.
  1085. sink.init(false, false, this.responsePipeSegmentSize, PR_UINT32_MAX, null);
  1086. // Add listener for the response body.
  1087. let newListener = new NetworkResponseListener(this, httpActivity);
  1088. // Remember the input stream, so it isn't released by GC.
  1089. newListener.inputStream = sink.inputStream;
  1090. newListener.sink = sink;
  1091. let tee = Cc["@mozilla.org/network/stream-listener-tee;1"]
  1092. .createInstance(Ci.nsIStreamListenerTee);
  1093. let originalListener = channel.setNewListener(tee);
  1094. tee.init(originalListener, sink.outputStream, newListener);
  1095. },
  1096. /**
  1097. * Handler for ACTIVITY_SUBTYPE_REQUEST_BODY_SENT. The request body is logged
  1098. * here.
  1099. *
  1100. * @private
  1101. * @param object httpActivity
  1102. * The HTTP activity object we are working with.
  1103. */
  1104. _onRequestBodySent: function (httpActivity) {
  1105. // Return early if we don't need the request body, or if we've
  1106. // already found it.
  1107. if (httpActivity.discardRequestBody || httpActivity.sentBody !== null) {
  1108. return;
  1109. }
  1110. let sentBody = NetworkHelper.readPostTextFromRequest(httpActivity.channel,
  1111. httpActivity.charset);
  1112. if (sentBody !== null && this.window &&
  1113. httpActivity.url == this.window.location.href) {
  1114. // If the request URL is the same as the current page URL, then
  1115. // we can try to get the posted text from the page directly.
  1116. // This check is necessary as otherwise the
  1117. // NetworkHelper.readPostTextFromPageViaWebNav()
  1118. // function is called for image requests as well but these
  1119. // are not web pages and as such don't store the posted text
  1120. // in the cache of the webpage.
  1121. let webNav = this.window.QueryInterface(Ci.nsIInterfaceRequestor)
  1122. .getInterface(Ci.nsIWebNavigation);
  1123. sentBody = NetworkHelper
  1124. .readPostTextFromPageViaWebNav(webNav, httpActivity.charset);
  1125. }
  1126. if (sentBody !== null) {
  1127. httpActivity.sentBody = sentBody;
  1128. }
  1129. },
  1130. /**
  1131. * Handler for ACTIVITY_SUBTYPE_RESPONSE_HEADER. This method stores
  1132. * information about the response headers.
  1133. *
  1134. * @private
  1135. * @param object httpActivity
  1136. * The HTTP activity object we are working with.
  1137. * @param string extraStringData
  1138. * The uncached response headers.
  1139. */
  1140. _onResponseHeader: function (httpActivity, extraStringData) {
  1141. // extraStringData contains the uncached response headers. The first line
  1142. // contains the response status (e.g. HTTP/1.1 200 OK).
  1143. //
  1144. // Note: The response header is not saved here. Calling the
  1145. // channel.visitResponseHeaders() method at this point sometimes causes an
  1146. // NS_ERROR_NOT_AVAILABLE exception.
  1147. //
  1148. // We could parse extraStringData to get the headers and their values, but
  1149. // that is not trivial to do in an accurate manner. Hence, we save the
  1150. // response headers in this._httpResponseExaminer().
  1151. let headers = extraStringData.split(/\r\n|\n|\r/);
  1152. let statusLine = headers.shift();
  1153. let statusLineArray = statusLine.split(" ");
  1154. let response = {};
  1155. response.httpVersion = statusLineArray.shift();
  1156. // XXX:
  1157. // Sometimes, when using a proxy server (manual proxy configuration),
  1158. // throws an error:
  1159. // 0x80040111 (NS_ERROR_NOT_AVAILABLE)
  1160. // [nsIHttpChannelInternal.remoteAddress]
  1161. // Bug 1337791 is the suspect.
  1162. response.remoteAddress = null;
  1163. try {
  1164. response.remoteAddress = httpActivity.channel.remoteAddress;
  1165. } catch (e) {
  1166. Cu.reportError(e);
  1167. }
  1168. response.remotePort = null;
  1169. try {
  1170. response.remotePort = httpActivity.channel.remotePort;
  1171. } catch (e) {
  1172. Cu.reportError(e);
  1173. }
  1174. response.status = statusLineArray.shift();
  1175. response.statusText = statusLineArray.join(" ");
  1176. response.headersSize = extraStringData.length;
  1177. httpActivity.responseStatus = response.status;
  1178. // Discard the response body for known response statuses.
  1179. switch (parseInt(response.status, 10)) {
  1180. case HTTP_MOVED_PERMANENTLY:
  1181. case HTTP_FOUND:
  1182. case HTTP_SEE_OTHER:
  1183. case HTTP_TEMPORARY_REDIRECT:
  1184. httpActivity.discardResponseBody = true;
  1185. break;
  1186. }
  1187. response.discardResponseBody = httpActivity.discardResponseBody;
  1188. httpActivity.owner.addResponseStart(response, extraStringData);
  1189. },
  1190. /**
  1191. * Handler for ACTIVITY_SUBTYPE_TRANSACTION_CLOSE. This method updates the HAR
  1192. * timing information on the HTTP activity object and clears the request
  1193. * from the list of known open requests.
  1194. *
  1195. * @private
  1196. * @param object httpActivity
  1197. * The HTTP activity object we work with.
  1198. */
  1199. _onTransactionClose: function (httpActivity) {
  1200. let result = this._setupHarTimings(httpActivity);
  1201. httpActivity.owner.addEventTimings(result.total, result.timings);
  1202. delete this.openRequests[httpActivity.id];
  1203. },
  1204. /**
  1205. * Update the HTTP activity object to include timing information as in the HAR
  1206. * spec. The HTTP activity object holds the raw timing information in
  1207. * |timings| - these are timings stored for each activity notification. The
  1208. * HAR timing information is constructed based on these lower level
  1209. * data.
  1210. *
  1211. * @param object httpActivity
  1212. * The HTTP activity object we are working with.
  1213. * @param boolean fromCache
  1214. * Indicates that the result was returned from the browser cache
  1215. * @return object
  1216. * This object holds two properties:
  1217. * - total - the total time for all of the request and response.
  1218. * - timings - the HAR timings object.
  1219. */
  1220. _setupHarTimings: function (httpActivity, fromCache) {
  1221. if (fromCache) {
  1222. // If it came from the browser cache, we have no timing
  1223. // information and these should all be 0
  1224. return {
  1225. total: 0,
  1226. timings: {
  1227. blocked: 0,
  1228. dns: 0,
  1229. ssl: 0,
  1230. connect: 0,
  1231. send: 0,
  1232. wait: 0,
  1233. receive: 0
  1234. }
  1235. };
  1236. }
  1237. let timings = httpActivity.timings;
  1238. let harTimings = {};
  1239. if (timings.STATUS_RESOLVING && timings.STATUS_CONNECTING_TO) {
  1240. harTimings.blocked = timings.STATUS_RESOLVING.first -
  1241. timings.REQUEST_HEADER.first;
  1242. } else if (timings.STATUS_SENDING_TO) {
  1243. harTimings.blocked = timings.STATUS_SENDING_TO.first -
  1244. timings.REQUEST_HEADER.first;
  1245. } else {
  1246. harTimings.blocked = -1;
  1247. }
  1248. // DNS timing information is available only in when the DNS record is not
  1249. // cached.
  1250. harTimings.dns = timings.STATUS_RESOLVING && timings.STATUS_RESOLVED ?
  1251. timings.STATUS_RESOLVED.last -
  1252. timings.STATUS_RESOLVING.first : -1;
  1253. if (timings.STATUS_CONNECTING_TO && timings.STATUS_CONNECTED_TO) {
  1254. harTimings.connect = timings.STATUS_CONNECTED_TO.last -
  1255. timings.STATUS_CONNECTING_TO.first;
  1256. } else {
  1257. harTimings.connect = -1;
  1258. }
  1259. if (timings.STATUS_TLS_STARTING && timings.STATUS_TLS_ENDING) {
  1260. harTimings.ssl = timings.STATUS_TLS_ENDING.last -
  1261. timings.STATUS_TLS_STARTING.first;
  1262. } else {
  1263. harTimings.ssl = -1;
  1264. }
  1265. // sometimes the connection information events are attached to a speculative
  1266. // channel instead of this one, but necko might glue them back together in the
  1267. // nsITimedChannel interface used by Resource and Navigation Timing
  1268. let timedChannel = httpActivity.channel.QueryInterface(Ci.nsITimedChannel);
  1269. if ((harTimings.connect <= 0) && timedChannel) {
  1270. if (timedChannel.secureConnectionStartTime > timedChannel.connectStartTime) {
  1271. harTimings.connect =
  1272. timedChannel.secureConnectionStartTime - timedChannel.connectStartTime;
  1273. harTimings.ssl =
  1274. timedChannel.connectEndTime - timedChannel.secureConnectionStartTime;
  1275. } else {
  1276. harTimings.connect =
  1277. timedChannel.connectEndTime - timedChannel.connectStartTime;
  1278. harTimings.ssl = -1;
  1279. }
  1280. }
  1281. if ((harTimings.dns <= 0) && timedChannel) {
  1282. harTimings.dns =
  1283. timedChannel.domainLookupEndTime - timedChannel.domainLookupStartTime;
  1284. }
  1285. if (timings.STATUS_SENDING_TO) {
  1286. harTimings.send = timings.STATUS_SENDING_TO.last - timings.STATUS_SENDING_TO.first;
  1287. } else if (timings.REQUEST_HEADER && timings.REQUEST_BODY_SENT) {
  1288. harTimings.send = timings.REQUEST_BODY_SENT.last - timings.REQUEST_HEADER.first;
  1289. } else {
  1290. harTimings.send = -1;
  1291. }
  1292. if (timings.RESPONSE_START) {
  1293. harTimings.wait = timings.RESPONSE_START.first -
  1294. (timings.REQUEST_BODY_SENT ||
  1295. timings.STATUS_SENDING_TO).last;
  1296. } else {
  1297. harTimings.wait = -1;
  1298. }
  1299. if (timings.RESPONSE_START && timings.RESPONSE_COMPLETE) {
  1300. harTimings.receive = timings.RESPONSE_COMPLETE.last -
  1301. timings.RESPONSE_START.first;
  1302. } else {
  1303. harTimings.receive = -1;
  1304. }
  1305. let totalTime = 0;
  1306. for (let timing in harTimings) {
  1307. let time = Math.max(Math.round(harTimings[timing] / 1000), -1);
  1308. harTimings[timing] = time;
  1309. if (time > -1) {
  1310. totalTime += time;
  1311. }
  1312. }
  1313. return {
  1314. total: totalTime,
  1315. timings: harTimings,
  1316. };
  1317. },
  1318. /**
  1319. * Suspend Web Console activity. This is called when all Web Consoles are
  1320. * closed.
  1321. */
  1322. destroy: function () {
  1323. if (Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT) {
  1324. gActivityDistributor.removeObserver(this);
  1325. Services.obs.removeObserver(this._httpResponseExaminer,
  1326. "http-on-examine-response");
  1327. Services.obs.removeObserver(this._httpResponseExaminer,
  1328. "http-on-examine-cached-response");
  1329. Services.obs.removeObserver(this._httpModifyExaminer,
  1330. "http-on-modify-request", false);
  1331. }
  1332. Services.obs.removeObserver(this._serviceWorkerRequest,
  1333. "service-worker-synthesized-response");
  1334. this.interceptedChannels.clear();
  1335. this.openRequests = {};
  1336. this.openResponses = {};
  1337. this.owner = null;
  1338. this.filters = null;
  1339. this._throttler = null;
  1340. },
  1341. };
  1342. /**
  1343. * The NetworkMonitorChild is used to proxy all of the network activity of the
  1344. * child app process from the main process. The child WebConsoleActor creates an
  1345. * instance of this object.
  1346. *
  1347. * Network requests for apps happen in the main process. As such,
  1348. * a NetworkMonitor instance is used by the WebappsActor in the main process to
  1349. * log the network requests for this child process.
  1350. *
  1351. * The main process creates NetworkEventActorProxy instances per request. These
  1352. * send the data to this object using the nsIMessageManager. Here we proxy the
  1353. * data to the WebConsoleActor or to a NetworkEventActor.
  1354. *
  1355. * @constructor
  1356. * @param number appId
  1357. * The web appId of the child process.
  1358. * @param number outerWindowID
  1359. * The outerWindowID of the TabActor's main window.
  1360. * @param nsIMessageManager messageManager
  1361. * The nsIMessageManager to use to communicate with the parent process.
  1362. * @param object DebuggerServerConnection
  1363. * The RDP connection to the client.
  1364. * @param object owner
  1365. * The WebConsoleActor that is listening for the network requests.
  1366. */
  1367. function NetworkMonitorChild(appId, outerWindowID, messageManager, conn, owner) {
  1368. this.appId = appId;
  1369. this.outerWindowID = outerWindowID;
  1370. this.conn = conn;
  1371. this.owner = owner;
  1372. this._messageManager = messageManager;
  1373. this._onNewEvent = this._onNewEvent.bind(this);
  1374. this._onUpdateEvent = this._onUpdateEvent.bind(this);
  1375. this._netEvents = new Map();
  1376. this._msgName = `debug:${this.conn.prefix}netmonitor`;
  1377. }
  1378. exports.NetworkMonitorChild = NetworkMonitorChild;
  1379. NetworkMonitorChild.prototype = {
  1380. appId: null,
  1381. owner: null,
  1382. _netEvents: null,
  1383. _saveRequestAndResponseBodies: true,
  1384. _throttleData: null,
  1385. get saveRequestAndResponseBodies() {
  1386. return this._saveRequestAndResponseBodies;
  1387. },
  1388. set saveRequestAndResponseBodies(val) {
  1389. this._saveRequestAndResponseBodies = val;
  1390. this._messageManager.sendAsyncMessage(this._msgName, {
  1391. action: "setPreferences",
  1392. preferences: {
  1393. saveRequestAndResponseBodies: this._saveRequestAndResponseBodies,
  1394. },
  1395. });
  1396. },
  1397. get throttleData() {
  1398. return this._throttleData;
  1399. },
  1400. set throttleData(val) {
  1401. this._throttleData = val;
  1402. this._messageManager.sendAsyncMessage(this._msgName, {
  1403. action: "setPreferences",
  1404. preferences: {
  1405. throttleData: this._throttleData,
  1406. },
  1407. });
  1408. },
  1409. init: function () {
  1410. this.conn.setupInParent({
  1411. module: "devtools/shared/webconsole/network-monitor",
  1412. setupParent: "setupParentProcess"
  1413. });
  1414. let mm = this._messageManager;
  1415. mm.addMessageListener(`${this._msgName}:newEvent`, this._onNewEvent);
  1416. mm.addMessageListener(`${this._msgName}:updateEvent`, this._onUpdateEvent);
  1417. mm.sendAsyncMessage(this._msgName, {
  1418. appId: this.appId,
  1419. outerWindowID: this.outerWindowID,
  1420. action: "start",
  1421. });
  1422. },
  1423. _onNewEvent: DevToolsUtils.makeInfallible(function _onNewEvent(msg) {
  1424. let {id, event} = msg.data;
  1425. // Try to add stack trace to the event data received from parent
  1426. if (this.owner.stackTraceCollector) {
  1427. event.cause.stacktrace =
  1428. this.owner.stackTraceCollector.getStackTrace(event.channelId);
  1429. }
  1430. let actor = this.owner.onNetworkEvent(event);
  1431. this._netEvents.set(id, Cu.getWeakReference(actor));
  1432. }),
  1433. _onUpdateEvent: DevToolsUtils.makeInfallible(function _onUpdateEvent(msg) {
  1434. let {id, method, args} = msg.data;
  1435. let weakActor = this._netEvents.get(id);
  1436. let actor = weakActor ? weakActor.get() : null;
  1437. if (!actor) {
  1438. console.error(`Received ${this._msgName}:updateEvent for unknown event ID: ${id}`);
  1439. return;
  1440. }
  1441. if (!(method in actor)) {
  1442. console.error(`Received ${this._msgName}:updateEvent unsupported ` +
  1443. `method: ${method}`);
  1444. return;
  1445. }
  1446. actor[method].apply(actor, args);
  1447. }),
  1448. destroy: function () {
  1449. let mm = this._messageManager;
  1450. try {
  1451. mm.removeMessageListener(`${this._msgName}:newEvent`, this._onNewEvent);
  1452. mm.removeMessageListener(`${this._msgName}:updateEvent`, this._onUpdateEvent);
  1453. } catch (e) {
  1454. // On b2g, when registered to a new root docshell,
  1455. // all message manager functions throw when trying to call them during
  1456. // message-manager-disconnect event.
  1457. // As there is no attribute/method on message manager to know
  1458. // if they are still usable or not, we can only catch the exception...
  1459. }
  1460. this._netEvents.clear();
  1461. this._messageManager = null;
  1462. this.conn = null;
  1463. this.owner = null;
  1464. },
  1465. };
  1466. /**
  1467. * The NetworkEventActorProxy is used to send network request information from
  1468. * the main process to the child app process. One proxy is used per request.
  1469. * Similarly, one NetworkEventActor in the child app process is used per
  1470. * request. The client receives all network logs from the child actors.
  1471. *
  1472. * The child process has a NetworkMonitorChild instance that is listening for
  1473. * all network logging from the main process. The net monitor shim is used to
  1474. * proxy the data to the WebConsoleActor instance of the child process.
  1475. *
  1476. * @constructor
  1477. * @param nsIMessageManager messageManager
  1478. * The message manager for the child app process. This is used for
  1479. * communication with the NetworkMonitorChild instance of the process.
  1480. * @param string msgName
  1481. * The message name to be used for this connection.
  1482. */
  1483. function NetworkEventActorProxy(messageManager, msgName) {
  1484. this.id = gSequenceId();
  1485. this.messageManager = messageManager;
  1486. this._msgName = msgName;
  1487. }
  1488. exports.NetworkEventActorProxy = NetworkEventActorProxy;
  1489. NetworkEventActorProxy.methodFactory = function (method) {
  1490. return DevToolsUtils.makeInfallible(function () {
  1491. let args = Array.slice(arguments);
  1492. let mm = this.messageManager;
  1493. mm.sendAsyncMessage(`${this._msgName}:updateEvent`, {
  1494. id: this.id,
  1495. method: method,
  1496. args: args,
  1497. });
  1498. }, "NetworkEventActorProxy." + method);
  1499. };
  1500. NetworkEventActorProxy.prototype = {
  1501. /**
  1502. * Initialize the network event. This method sends the network request event
  1503. * to the content process.
  1504. *
  1505. * @param object event
  1506. * Object describing the network request.
  1507. * @return object
  1508. * This object.
  1509. */
  1510. init: DevToolsUtils.makeInfallible(function (event) {
  1511. let mm = this.messageManager;
  1512. mm.sendAsyncMessage(`${this._msgName}:newEvent`, {
  1513. id: this.id,
  1514. event: event,
  1515. });
  1516. return this;
  1517. }),
  1518. };
  1519. (function () {
  1520. // Listeners for new network event data coming from the NetworkMonitor.
  1521. let methods = ["addRequestHeaders", "addRequestCookies", "addRequestPostData",
  1522. "addResponseStart", "addSecurityInfo", "addResponseHeaders",
  1523. "addResponseCookies", "addResponseContent", "addEventTimings"];
  1524. let factory = NetworkEventActorProxy.methodFactory;
  1525. for (let method of methods) {
  1526. NetworkEventActorProxy.prototype[method] = factory(method);
  1527. }
  1528. })();
  1529. /**
  1530. * This is triggered by the child calling `setupInParent` when the child's network monitor
  1531. * is starting up. This initializes the parent process side of the monitoring.
  1532. */
  1533. function setupParentProcess({ mm, prefix }) {
  1534. let networkMonitor = new NetworkMonitorParent(mm, prefix);
  1535. return {
  1536. onBrowserSwap: newMM => networkMonitor.setMessageManager(newMM),
  1537. onDisconnected: () => {
  1538. networkMonitor.destroy();
  1539. networkMonitor = null;
  1540. }
  1541. };
  1542. }
  1543. exports.setupParentProcess = setupParentProcess;
  1544. /**
  1545. * The NetworkMonitorParent runs in the parent process and uses the message manager to
  1546. * listen for requests from the child process to start/stop the network monitor. Most
  1547. * request data is only available from the parent process, so that's why the network
  1548. * monitor needs to run there when debugging tabs that are in the child.
  1549. *
  1550. * @param nsIMessageManager mm
  1551. * The message manager for the browser we're filtering on.
  1552. * @param string prefix
  1553. * The RDP connection prefix that uniquely identifies the connection.
  1554. */
  1555. function NetworkMonitorParent(mm, prefix) {
  1556. this._msgName = `debug:${prefix}netmonitor`;
  1557. this.onNetMonitorMessage = this.onNetMonitorMessage.bind(this);
  1558. this.onNetworkEvent = this.onNetworkEvent.bind(this);
  1559. this.setMessageManager(mm);
  1560. }
  1561. NetworkMonitorParent.prototype = {
  1562. netMonitor: null,
  1563. messageManager: null,
  1564. setMessageManager(mm) {
  1565. if (this.messageManager) {
  1566. let oldMM = this.messageManager;
  1567. oldMM.removeMessageListener(this._msgName, this.onNetMonitorMessage);
  1568. }
  1569. this.messageManager = mm;
  1570. if (mm) {
  1571. mm.addMessageListener(this._msgName, this.onNetMonitorMessage);
  1572. }
  1573. },
  1574. /**
  1575. * Handler for `debug:${prefix}netmonitor` messages received through the message manager
  1576. * from the content process.
  1577. *
  1578. * @param object msg
  1579. * Message from the content.
  1580. */
  1581. onNetMonitorMessage: DevToolsUtils.makeInfallible(function (msg) {
  1582. let {action} = msg.json;
  1583. // Pipe network monitor data from parent to child via the message manager.
  1584. switch (action) {
  1585. case "start":
  1586. if (!this.netMonitor) {
  1587. let {appId, outerWindowID} = msg.json;
  1588. this.netMonitor = new NetworkMonitor({
  1589. outerWindowID,
  1590. appId,
  1591. }, this);
  1592. this.netMonitor.init();
  1593. }
  1594. break;
  1595. case "setPreferences": {
  1596. let {preferences} = msg.json;
  1597. for (let key of Object.keys(preferences)) {
  1598. if ((key == "saveRequestAndResponseBodies" ||
  1599. key == "throttleData") && this.netMonitor) {
  1600. this.netMonitor[key] = preferences[key];
  1601. }
  1602. }
  1603. break;
  1604. }
  1605. case "stop":
  1606. if (this.netMonitor) {
  1607. this.netMonitor.destroy();
  1608. this.netMonitor = null;
  1609. }
  1610. break;
  1611. case "disconnect":
  1612. this.destroy();
  1613. break;
  1614. }
  1615. }),
  1616. /**
  1617. * Handler for new network requests. This method is invoked by the current
  1618. * NetworkMonitor instance.
  1619. *
  1620. * @param object event
  1621. * Object describing the network request.
  1622. * @return object
  1623. * A NetworkEventActorProxy instance which is notified when further
  1624. * data about the request is available.
  1625. */
  1626. onNetworkEvent: DevToolsUtils.makeInfallible(function (event) {
  1627. return new NetworkEventActorProxy(this.messageManager, this._msgName).init(event);
  1628. }),
  1629. destroy: function () {
  1630. this.setMessageManager(null);
  1631. if (this.netMonitor) {
  1632. this.netMonitor.destroy();
  1633. this.netMonitor = null;
  1634. }
  1635. },
  1636. };
  1637. /**
  1638. * A WebProgressListener that listens for location changes.
  1639. *
  1640. * This progress listener is used to track file loads and other kinds of
  1641. * location changes.
  1642. *
  1643. * @constructor
  1644. * @param object window
  1645. * The window for which we need to track location changes.
  1646. * @param object owner
  1647. * The listener owner which needs to implement two methods:
  1648. * - onFileActivity(aFileURI)
  1649. * - onLocationChange(aState, aTabURI, aPageTitle)
  1650. */
  1651. function ConsoleProgressListener(window, owner) {
  1652. this.window = window;
  1653. this.owner = owner;
  1654. }
  1655. exports.ConsoleProgressListener = ConsoleProgressListener;
  1656. ConsoleProgressListener.prototype = {
  1657. /**
  1658. * Constant used for startMonitor()/stopMonitor() that tells you want to
  1659. * monitor file loads.
  1660. */
  1661. MONITOR_FILE_ACTIVITY: 1,
  1662. /**
  1663. * Constant used for startMonitor()/stopMonitor() that tells you want to
  1664. * monitor page location changes.
  1665. */
  1666. MONITOR_LOCATION_CHANGE: 2,
  1667. /**
  1668. * Tells if you want to monitor file activity.
  1669. * @private
  1670. * @type boolean
  1671. */
  1672. _fileActivity: false,
  1673. /**
  1674. * Tells if you want to monitor location changes.
  1675. * @private
  1676. * @type boolean
  1677. */
  1678. _locationChange: false,
  1679. /**
  1680. * Tells if the console progress listener is initialized or not.
  1681. * @private
  1682. * @type boolean
  1683. */
  1684. _initialized: false,
  1685. _webProgress: null,
  1686. QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
  1687. Ci.nsISupportsWeakReference]),
  1688. /**
  1689. * Initialize the ConsoleProgressListener.
  1690. * @private
  1691. */
  1692. _init: function () {
  1693. if (this._initialized) {
  1694. return;
  1695. }
  1696. this._webProgress = this.window.QueryInterface(Ci.nsIInterfaceRequestor)
  1697. .getInterface(Ci.nsIWebNavigation)
  1698. .QueryInterface(Ci.nsIWebProgress);
  1699. this._webProgress.addProgressListener(this,
  1700. Ci.nsIWebProgress.NOTIFY_STATE_ALL);
  1701. this._initialized = true;
  1702. },
  1703. /**
  1704. * Start a monitor/tracker related to the current nsIWebProgressListener
  1705. * instance.
  1706. *
  1707. * @param number monitor
  1708. * Tells what you want to track. Available constants:
  1709. * - this.MONITOR_FILE_ACTIVITY
  1710. * Track file loads.
  1711. * - this.MONITOR_LOCATION_CHANGE
  1712. * Track location changes for the top window.
  1713. */
  1714. startMonitor: function (monitor) {
  1715. switch (monitor) {
  1716. case this.MONITOR_FILE_ACTIVITY:
  1717. this._fileActivity = true;
  1718. break;
  1719. case this.MONITOR_LOCATION_CHANGE:
  1720. this._locationChange = true;
  1721. break;
  1722. default:
  1723. throw new Error("ConsoleProgressListener: unknown monitor type " +
  1724. monitor + "!");
  1725. }
  1726. this._init();
  1727. },
  1728. /**
  1729. * Stop a monitor.
  1730. *
  1731. * @param number monitor
  1732. * Tells what you want to stop tracking. See this.startMonitor() for
  1733. * the list of constants.
  1734. */
  1735. stopMonitor: function (monitor) {
  1736. switch (monitor) {
  1737. case this.MONITOR_FILE_ACTIVITY:
  1738. this._fileActivity = false;
  1739. break;
  1740. case this.MONITOR_LOCATION_CHANGE:
  1741. this._locationChange = false;
  1742. break;
  1743. default:
  1744. throw new Error("ConsoleProgressListener: unknown monitor type " +
  1745. monitor + "!");
  1746. }
  1747. if (!this._fileActivity && !this._locationChange) {
  1748. this.destroy();
  1749. }
  1750. },
  1751. onStateChange: function (progress, request, state, status) {
  1752. if (!this.owner) {
  1753. return;
  1754. }
  1755. if (this._fileActivity) {
  1756. this._checkFileActivity(progress, request, state, status);
  1757. }
  1758. if (this._locationChange) {
  1759. this._checkLocationChange(progress, request, state, status);
  1760. }
  1761. },
  1762. /**
  1763. * Check if there is any file load, given the arguments of
  1764. * nsIWebProgressListener.onStateChange. If the state change tells that a file
  1765. * URI has been loaded, then the remote Web Console instance is notified.
  1766. * @private
  1767. */
  1768. _checkFileActivity: function (progress, request, state, status) {
  1769. if (!(state & Ci.nsIWebProgressListener.STATE_START)) {
  1770. return;
  1771. }
  1772. let uri = null;
  1773. if (request instanceof Ci.imgIRequest) {
  1774. let imgIRequest = request.QueryInterface(Ci.imgIRequest);
  1775. uri = imgIRequest.URI;
  1776. } else if (request instanceof Ci.nsIChannel) {
  1777. let nsIChannel = request.QueryInterface(Ci.nsIChannel);
  1778. uri = nsIChannel.URI;
  1779. }
  1780. if (!uri || !uri.schemeIs("file") && !uri.schemeIs("ftp")) {
  1781. return;
  1782. }
  1783. this.owner.onFileActivity(uri.spec);
  1784. },
  1785. /**
  1786. * Check if the current window.top location is changing, given the arguments
  1787. * of nsIWebProgressListener.onStateChange. If that is the case, the remote
  1788. * Web Console instance is notified.
  1789. * @private
  1790. */
  1791. _checkLocationChange: function (progress, request, state) {
  1792. let isStart = state & Ci.nsIWebProgressListener.STATE_START;
  1793. let isStop = state & Ci.nsIWebProgressListener.STATE_STOP;
  1794. let isNetwork = state & Ci.nsIWebProgressListener.STATE_IS_NETWORK;
  1795. let isWindow = state & Ci.nsIWebProgressListener.STATE_IS_WINDOW;
  1796. // Skip non-interesting states.
  1797. if (!isNetwork || !isWindow || progress.DOMWindow != this.window) {
  1798. return;
  1799. }
  1800. if (isStart && request instanceof Ci.nsIChannel) {
  1801. this.owner.onLocationChange("start", request.URI.spec, "");
  1802. } else if (isStop) {
  1803. this.owner.onLocationChange("stop", this.window.location.href,
  1804. this.window.document.title);
  1805. }
  1806. },
  1807. onLocationChange: function () {},
  1808. onStatusChange: function () {},
  1809. onProgressChange: function () {},
  1810. onSecurityChange: function () {},
  1811. /**
  1812. * Destroy the ConsoleProgressListener.
  1813. */
  1814. destroy: function () {
  1815. if (!this._initialized) {
  1816. return;
  1817. }
  1818. this._initialized = false;
  1819. this._fileActivity = false;
  1820. this._locationChange = false;
  1821. try {
  1822. this._webProgress.removeProgressListener(this);
  1823. } catch (ex) {
  1824. // This can throw during browser shutdown.
  1825. }
  1826. this._webProgress = null;
  1827. this.window = null;
  1828. this.owner = null;
  1829. },
  1830. };
  1831. function gSequenceId() {
  1832. return gSequenceId.n++;
  1833. }
  1834. gSequenceId.n = 1;