summaryrefslogtreecommitdiffstats
path: root/comm/mailnews/news/src/NntpChannel.jsm
blob: 4e20fca7bce4c3db53ec95db2df5d17b4626012f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/* 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/. */

const EXPORTED_SYMBOLS = ["NntpChannel"];

const { MailChannel } = ChromeUtils.importESModule(
  "resource:///modules/MailChannel.sys.mjs"
);
const { MailServices } = ChromeUtils.import(
  "resource:///modules/MailServices.jsm"
);
const { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);

const lazy = {};

XPCOMUtils.defineLazyModuleGetters(lazy, {
  MailUtils: "resource:///modules/MailUtils.jsm",
  NntpUtils: "resource:///modules/NntpUtils.jsm",
});

/**
 * A channel to interact with NNTP server.
 *
 * @implements {nsIChannel}
 * @implements {nsIRequest}
 * @implements {nsICacheEntryOpenCallback}
 */
class NntpChannel extends MailChannel {
  QueryInterface = ChromeUtils.generateQI([
    "nsIMailChannel",
    "nsIChannel",
    "nsIRequest",
    "nsICacheEntryOpenCallback",
  ]);

  _logger = lazy.NntpUtils.logger;
  _status = Cr.NS_OK;

  /**
   * @param {nsIURI} uri - The uri to construct the channel from.
   * @param {nsILoadInfo} [loadInfo] - The loadInfo associated with the channel.
   */
  constructor(uri, loadInfo) {
    super();
    this._server = lazy.NntpUtils.findServer(uri.asciiHost);
    if (!this._server) {
      this._server = MailServices.accounts
        .createIncomingServer("", uri.asciiHost, "nntp")
        .QueryInterface(Ci.nsINntpIncomingServer);
      this._server.port = uri.port;
    }

    if (uri.port < 1) {
      // Ensure the uri has a port so that memory cache works.
      uri = uri.mutate().setPort(this._server.port).finalize();
    }

    // Two forms of the uri:
    // - news://news.mozilla.org:119/mailman.30.1608649442.1056.accessibility%40lists.mozilla.org?group=mozilla.accessibility&key=378
    // - news://news.mozilla.org:119/id@mozilla.org
    let url = new URL(uri.spec);
    this._groupName = url.searchParams.get("group");
    if (this._groupName) {
      this._newsFolder = this._server.rootFolder.getChildNamed(
        decodeURIComponent(url.searchParams.get("group"))
      );
      this._articleNumber = url.searchParams.get("key");
    } else {
      this._messageId = decodeURIComponent(url.pathname.slice(1));
      if (!this._messageId.includes("@")) {
        this._groupName = this._messageId;
        this._messageId = null;
      }
    }

    // nsIChannel attributes.
    this.originalURI = uri;
    this.URI = uri.QueryInterface(Ci.nsIMsgMailNewsUrl);
    this.loadInfo = loadInfo || {
      QueryInterface: ChromeUtils.generateQI(["nsILoadInfo"]),
      loadingPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
      securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
      internalContentPolicy: Ci.nsIContentPolicy.TYPE_OTHER,
    };
    this.contentLength = 0;
  }

  /**
   * @see nsIRequest
   * @returns {string}
   */
  get name() {
    return this.URI?.spec;
  }

  /**
   * @see nsIRequest
   * @returns {boolean}
   */
  isPending() {
    return !!this._pending;
  }

  /**
   * @see nsIRequest
   * @returns {nsresult}
   */
  get status() {
    return this._status;
  }

  /**
   * @see nsICacheEntryOpenCallback
   */
  onCacheEntryAvailable(entry, isNew, status) {
    if (!Components.isSuccessCode(status)) {
      // If memory cache doesn't work, read from the server.
      this._readFromServer();
      return;
    }

    if (isNew) {
      if (Services.io.offline) {
        this._status = Cr.NS_ERROR_OFFLINE;
        return;
      }
      // It's a new entry, needs to read from the server.
      let tee = Cc["@mozilla.org/network/stream-listener-tee;1"].createInstance(
        Ci.nsIStreamListenerTee
      );
      let outStream = entry.openOutputStream(0, -1);
      // When the tee stream receives data from the server, it writes to both
      // the original listener and outStream (memory cache).
      tee.init(this._listener, outStream, null);
      this._listener = tee;
      this._cacheEntry = entry;
      this._readFromServer();
      return;
    }

    // It's an old entry, read from the memory cache.
    this._readFromCacheStream(entry.openInputStream(0));
  }

  onCacheEntryCheck(entry) {
    return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED;
  }

  /**
   * @see nsIChannel
   */
  get contentType() {
    return this._contentType || "message/rfc822";
  }

  set contentType(value) {
    this._contentType = value;
  }

  get isDocument() {
    return true;
  }

  open() {
    throw Components.Exception(
      `${this.constructor.name}.open not implemented`,
      Cr.NS_ERROR_NOT_IMPLEMENTED
    );
  }

  asyncOpen(listener) {
    this._logger.debug("asyncOpen", this.URI.spec);
    let url = new URL(this.URI.spec);
    this._listener = listener;
    if (url.searchParams.has("list-ids")) {
      // Triggered by newsError.js.
      this._removeExpired(decodeURIComponent(url.pathname.slice(1)));
      return;
    }

    if (this._groupName && !this._server.containsNewsgroup(this._groupName)) {
      let bundle = Services.strings.createBundle(
        "chrome://messenger/locale/news.properties"
      );
      let win = Services.wm.getMostRecentWindow("mail:3pane");
      let result = Services.prompt.confirm(
        win,
        null,
        bundle.formatStringFromName("autoSubscribeText", [this._groupName])
      );
      if (!result) {
        return;
      }
      this._server.subscribeToNewsgroup(this._groupName);
      let folder = this._server.findGroup(this._groupName);
      lazy.MailUtils.displayFolderIn3Pane(folder.URI);
    }

    if (this._groupName && !this._articleNumber && !this._messageId) {
      let folder = this._server.findGroup(this._groupName);
      lazy.MailUtils.displayFolderIn3Pane(folder.URI);
      return;
    }

    if (url.searchParams.has("part")) {
      let converter = Cc["@mozilla.org/streamConverters;1"].getService(
        Ci.nsIStreamConverterService
      );
      this._listener = converter.asyncConvertData(
        "message/rfc822",
        "*/*",
        listener,
        this
      );
    }
    try {
      // Attempt to get the message from the offline storage.
      try {
        if (this._readFromOfflineStorage()) {
          return;
        }
      } catch (e) {
        this._logger.warn(e);
      }

      let uri = this.URI;
      if (url.search) {
        // A full news url may look like
        // news://<host>:119/<Msg-ID>?group=<name>&key=<key>&header=quotebody.
        // Remove any query strings to keep the cache key stable.
        uri = uri.mutate().setQuery("").finalize();
      }

      // Check if a memory cache is available for the current URI.
      MailServices.nntp.cacheStorage.asyncOpenURI(
        uri,
        "",
        Ci.nsICacheStorage.OPEN_NORMALLY,
        this
      );
    } catch (e) {
      this._logger.warn(e);
      this._readFromServer();
    }
    if (this._status == Cr.NS_ERROR_OFFLINE) {
      throw new Components.Exception(
        "The requested action could not be completed in the offline state",
        Cr.NS_ERROR_OFFLINE
      );
    }
  }

  /**
   * Try to read the article from the offline storage.
   *
   * @returns {boolean} True if successfully read from the offline storage.
   */
  _readFromOfflineStorage() {
    if (!this._newsFolder) {
      return false;
    }
    if (!this._newsFolder.hasMsgOffline(this._articleNumber)) {
      return false;
    }
    let hdr = this._newsFolder.GetMessageHeader(this._articleNumber);
    let stream = this._newsFolder.getLocalMsgStream(hdr);
    this._readFromCacheStream(stream);
    return true;
  }

  /**
   * Read the article from the a stream.
   *
   * @param {nsIInputStream} cacheStream - The input stream to read.
   */
  _readFromCacheStream(cacheStream) {
    let pump = Cc["@mozilla.org/network/input-stream-pump;1"].createInstance(
      Ci.nsIInputStreamPump
    );
    this.contentLength = 0;
    this._contentType = "";
    pump.init(cacheStream, 0, 0, true);
    pump.asyncRead({
      onStartRequest: () => {
        this._listener.onStartRequest(this);
        this._pending = true;
      },
      onStopRequest: (request, status) => {
        this._listener.onStopRequest(this, status);
        try {
          this.loadGroup?.removeRequest(this, null, Cr.NS_OK);
        } catch (e) {}
        this._pending = false;
      },
      onDataAvailable: (request, stream, offset, count) => {
        this.contentLength += count;
        this._listener.onDataAvailable(this, stream, offset, count);
        try {
          if (!cacheStream.available()) {
            cacheStream.close();
          }
        } catch (e) {}
      },
    });
  }

  /**
   * Retrieve the article from the server.
   */
  _readFromServer() {
    this._logger.debug("Read from server");
    let pipe = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe);
    pipe.init(true, true, 0, 0);
    let inputStream = pipe.inputStream;
    let outputStream = pipe.outputStream;
    if (this._newsFolder) {
      this._newsFolder.QueryInterface(Ci.nsIMsgNewsFolder).saveArticleOffline =
        this._newsFolder.shouldStoreMsgOffline(this._articleNumber);
    }

    this._server.wrappedJSObject.withClient(client => {
      let msgWindow;
      try {
        msgWindow = this.URI.msgWindow;
      } catch (e) {}
      client.startRunningUrl(null, msgWindow, this.URI);
      client.channel = this;
      this._listener.onStartRequest(this);
      this._pending = true;
      client.onOpen = () => {
        if (this._messageId) {
          client.getArticleByMessageId(this._messageId);
        } else {
          client.getArticleByArticleNumber(
            this._groupName,
            this._articleNumber
          );
        }
      };

      client.onData = data => {
        this.contentLength += data.length;
        outputStream.write(data, data.length);
        this._listener.onDataAvailable(this, inputStream, 0, data.length);
      };

      client.onDone = status => {
        try {
          this.loadGroup?.removeRequest(this, null, Cr.NS_OK);
        } catch (e) {}
        if (status != Cr.NS_OK) {
          // Prevent marking a message as read.
          this.URI.errorCode = status;
          // Remove the invalid cache.
          this._cacheEntry?.asyncDoom(null);
        }
        this._listener.onStopRequest(this, status);
        this._newsFolder?.msgDatabase.commit(
          Ci.nsMsgDBCommitType.kSessionCommit
        );
        this._pending = false;
      };
    });
  }

  /**
   * Fetch all the article keys on the server, then remove expired keys from the
   * local folder.
   *
   * @param {string} groupName - The group to check.
   */
  _removeExpired(groupName) {
    this._logger.debug("_removeExpired", groupName);
    let newsFolder = this._server.findGroup(groupName);
    let allKeys = new Set(newsFolder.msgDatabase.listAllKeys());
    this._server.wrappedJSObject.withClient(client => {
      let msgWindow;
      try {
        msgWindow = this.URI.msgWindow;
      } catch (e) {}
      client.startRunningUrl(null, msgWindow, this.URI);
      this._listener.onStartRequest(this);
      this._pending = true;
      client.onOpen = () => {
        client.listgroup(groupName);
      };

      client.onData = data => {
        allKeys.delete(+data);
      };

      client.onDone = status => {
        newsFolder.removeMessages([...allKeys]);
        this._listener.onStopRequest(this, status);
        this._pending = false;
      };
    });
  }
}