ctb_workspace/
crlite.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MPL-2.0
2// SPDX-License-Identifier for parts derived from Mozilla Firefox and moz_crlite_query: MPL-2.0
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21/* This Source Code Form is subject to the terms of the Mozilla Public
22 * License, v. 2.0. If a copy of the MPL was not distributed with this
23 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
24
25// See additional licensing details at end of file.
26
27//! Workspace-owned `CRLite` cache access.
28
29#![allow(
30    clippy::filter_next,
31    clippy::unused_async,
32    reason = "uniform signature mapping and iteration patterns"
33)]
34
35#[allow(
36    unused_imports,
37    clippy::wildcard_imports,
38    reason = "Standard workspace module prelude"
39)]
40use crate::utilities::*;
41
42use ctb_utilities::https::crlite::{
43    DEFAULT_CRLITE_MAX_AGE, ensure_crlite_cache_ready_sync,
44    get_crlite_cache_dir, get_crlite_manifest_path,
45    load_crlite_collection_json, load_crlite_manifest, record_refresh_time,
46    refresh_crlite_cache_sync, should_rate_limit_refresh,
47    validate_relative_artifact_path,
48};
49use serde::Serialize;
50
51#[derive(Debug, Serialize)]
52struct CRLiteCacheStatus {
53    cache_dir: String,
54    manifest_path: String,
55    manifest_present: bool,
56    fresh: bool,
57    last_updated_unix_seconds: Option<u64>,
58    current_filter_relative_path: Option<String>,
59    delta_count: usize,
60    source_kind: Option<String>,
61}
62
63async fn ensure_crlite_cache_ready() -> Result<()> {
64    spawn_blocking_with_current_test_name(ensure_crlite_cache_ready_sync)
65        .await
66        .context("CRLite refresh task failed")??;
67    Ok(())
68}
69
70fn build_crlite_cache_status() -> Result<CRLiteCacheStatus> {
71    let cache_dir = get_crlite_cache_dir()?;
72    let manifest_path = get_crlite_manifest_path()?;
73    let manifest = load_crlite_manifest()?;
74
75    let (
76        manifest_present,
77        fresh,
78        last_updated_unix_seconds,
79        current_filter,
80        delta_count,
81    ) = if let Some(manifest) = manifest {
82        let fresh = manifest
83            .is_fresh(std::time::SystemTime::now(), DEFAULT_CRLITE_MAX_AGE);
84        (
85            true,
86            fresh,
87            Some(manifest.last_updated_unix_seconds),
88            manifest
89                .current_filter
90                .map(|artifact| artifact.relative_path),
91            manifest.deltas.len(),
92        )
93    } else {
94        (false, false, None, None, 0)
95    };
96
97    let source_kind = load_crlite_manifest()?
98        .map(|manifest| format!("{:?}", manifest.source.kind));
99
100    Ok(CRLiteCacheStatus {
101        cache_dir: cache_dir.display().to_string(),
102        manifest_path: manifest_path.display().to_string(),
103        manifest_present,
104        fresh,
105        last_updated_unix_seconds,
106        current_filter_relative_path: current_filter,
107        delta_count,
108        source_kind,
109    })
110}
111
112/// Returns `CRLite` cache status as JSON for the web controller or diagnostics.
113#[ipc_method]
114pub async fn get_crlite_cache_status() -> Result<String> {
115    ensure_crlite_cache_ready().await?;
116    let status = build_crlite_cache_status()?;
117    serde_json::to_string_pretty(&status)
118        .context("Failed to serialize CRLite cache status")
119}
120
121/// Returns the persisted `CRLite` manifest file as JSON.
122#[ipc_method]
123pub async fn get_crlite_manifest_json() -> Result<String> {
124    ensure_crlite_cache_ready().await?;
125    let json = load_crlite_collection_json()?
126        .ok_or_else(|| anyhow::anyhow!("CRLite collection JSON not cached"))?;
127    Ok(json)
128}
129
130/// Reads one cached `CRLite` artifact by relative path.
131#[ipc_method]
132pub async fn get_crlite_artifact(relative_path: &str) -> Result<Vec<u8>> {
133    ensure_crlite_cache_ready().await?;
134    let cache_dir = get_crlite_cache_dir()?;
135    let relative_path_buf = validate_relative_artifact_path(relative_path)?;
136    let absolute_path = cache_dir.join(&relative_path_buf);
137
138    let find_record = || -> Option<(std::path::PathBuf, u64, String)> {
139        let json = load_crlite_collection_json().ok()??;
140        let response = serde_json::from_str::<
141            ctb_utilities::https::crlite::CRLiteCollectionResponse,
142        >(&json)
143        .ok()?;
144        let record = response.data.iter().find(|r| {
145            r.attachment.location == relative_path
146                || r.attachment.filename == relative_path
147        })?;
148        let channel = record.channel_name();
149        let path = cache_dir.join(channel).join(&record.attachment.filename);
150        Some((path, record.attachment.size, record.attachment.hash.clone()))
151    };
152
153    let check_and_read = || -> Result<Option<Vec<u8>>> {
154        if let Some((path, size, hash)) = find_record() {
155            if let Ok(bytes) = std::fs::read(&path) {
156                let computed_hash =
157                    ctb_installer::chunking::compute_sha256_hex(&bytes);
158                if u64::try_from(bytes.len())? == size && computed_hash == hash
159                {
160                    return Ok(Some(bytes));
161                }
162                warn_fmt!(
163                    "CRLite artifact integrity check failed for {}",
164                    path.display()
165                );
166            } else {
167                warn_fmt!("CRLite artifact missing at {}", path.display());
168            }
169            Ok(None)
170        } else {
171            // Fall back to direct absolute path read if no collection record matches
172            if let Ok(bytes) = std::fs::read(&absolute_path) {
173                Ok(Some(bytes))
174            } else {
175                Ok(None)
176            }
177        }
178    };
179
180    if let Some(bytes) = check_and_read()? {
181        return Ok(bytes);
182    }
183
184    if should_rate_limit_refresh() {
185        return Err(anyhow::anyhow!(
186            "CRLite artifact not found or corrupted (refresh rate-limited)"
187        ));
188    }
189
190    warn_fmt!(
191        "Triggering CRLite cache refresh due to missing or corrupted artifact: {relative_path}"
192    );
193    record_refresh_time();
194    spawn_blocking_with_current_test_name(refresh_crlite_cache_sync)
195        .await
196        .context("CRLite refresh task failed")??;
197
198    if let Some(bytes) = check_and_read()? {
199        return Ok(bytes);
200    }
201
202    Err(anyhow::anyhow!(
203        "CRLite artifact not found or corrupted after refresh: {relative_path}"
204    ))
205}
206
207#[cfg(test)]
208#[allow(
209    clippy::panic,
210    clippy::expect_used,
211    clippy::unwrap_used,
212    clippy::unwrap_in_result,
213    clippy::panic_in_result_fn,
214    clippy::indexing_slicing,
215    clippy::arithmetic_side_effects,
216    reason = "Standard repository test boilerplate"
217)]
218mod tests {
219    use std::fs;
220
221    use axum::{
222        Router,
223        body::{Body, to_bytes},
224        http::{Method, Request, StatusCode},
225        routing::get,
226    };
227    use ctb_utilities::https::crlite::{
228        get_crlite_cache_dir, load_crlite_manifest, set_test_download_override,
229    };
230    use ctb_utilities::json::maybe_value::{MaybeOption, MaybeValue};
231    use ctb_utilities::pc_settings::PcSettings;
232    use ctb_utilities::{Context, Result, anyhow, ensure};
233    use tower::ServiceExt;
234
235    use super::{get_crlite_manifest_json, validate_relative_artifact_path};
236
237    fn fixture_path(name: &str) -> std::path::PathBuf {
238        ctb_utilities::manifest_fixture_path(
239            concat!(env!("CARGO_MANIFEST_DIR"), "/../utilities/https"),
240            &format!("test_crlite_filters/{name}"),
241        )
242    }
243
244    fn fixture_metadata(name: &str) -> (String, u64) {
245        let bytes = fs::read(fixture_path(name)).unwrap();
246        let hash = ctb_installer::chunking::compute_sha256_hex(&bytes);
247        let size = u64::try_from(bytes.len()).unwrap();
248        (hash, size)
249    }
250
251    fn manifest_json() -> String {
252        let (full_hash, full_size) = fixture_metadata("20200101-0-filter");
253        let (delta_hash, delta_size) =
254            fixture_metadata("20200101-1-filter.delta");
255        serde_json::json!({
256            "data": [
257                {
258                    "id": "full-filter",
259                    "channel": "default",
260                    "details": { "name": "2020-01-01T00:00:00Z-full" },
261                    "attachment": {
262                        "hash": full_hash,
263                        "size": full_size,
264                        "filename": "20200101-0-filter",
265                        "location": "default/20200101-0-filter",
266                        "mimetype": "application/octet-stream"
267                    },
268                    "incremental": false,
269                    "effectiveTimestamp": 1_577_836_800_000_i64
270                },
271                {
272                    "id": "delta-filter",
273                    "parent": "full-filter",
274                    "channel": "default",
275                    "details": { "name": "2020-01-02T00:00:00Z-diff" },
276                    "attachment": {
277                        "hash": delta_hash,
278                        "size": delta_size,
279                        "filename": "20200101-1-filter.delta",
280                        "location": "default/20200101-1-filter.delta",
281                        "mimetype": "application/octet-stream"
282                    },
283                    "incremental": true,
284                    "effectiveTimestamp": 1_577_923_200_000_i64
285                }
286            ]
287        })
288        .to_string()
289    }
290
291    fn request_uri_from_url(url: &str) -> Result<String> {
292        let Some(scheme_end) = url.find("://") else {
293            return Err(anyhow::anyhow!(
294                "CRLite test URL is missing a scheme: {url}"
295            ));
296        };
297        let after_scheme =
298            url.get(scheme_end.saturating_add(3)..).unwrap_or("");
299        let Some(path_start) = after_scheme.find('/') else {
300            return Ok("/".to_string());
301        };
302        Ok(after_scheme.get(path_start..).unwrap_or("").to_string())
303    }
304
305    #[crate::ctb_test]
306    fn rejects_parent_directory_components() {
307        let result = validate_relative_artifact_path("../outside.filter");
308        result.unwrap_err();
309    }
310
311    #[crate::ctb_test]
312    fn accepts_nested_relative_paths() {
313        let result = validate_relative_artifact_path("default/20260603.filter");
314        result.unwrap();
315    }
316
317    #[crate::ctb_test("tokio")]
318    async fn manifest_refreshes_cache_from_local_mirror() {
319        // It appears that `get_crlite_cache_dir()` appends the current test
320        // name, so it should be fine to not use a tempdir for this.
321        //bypass-tempdir-lint
322        let cache_dir = get_crlite_cache_dir().unwrap();
323        if cache_dir.exists() {
324            fs::remove_dir_all(&cache_dir).unwrap();
325        }
326
327        let manifest = manifest_json();
328
329        let mirror: Router =
330            Router::new()
331                .route(
332                    "/crlite/manifest.json",
333                    get({
334                        let manifest = manifest.clone();
335                        move || {
336                            let manifest = manifest.clone();
337                            async move { manifest }
338                        }
339                    }),
340                )
341                .route(
342                    "/crlite/artifacts/{*path}",
343                    get(
344                        |axum::extract::Path(path): axum::extract::Path<
345                            String,
346                        >| async move {
347                            let filename = std::path::Path::new(&path)
348                                .file_name()
349                                .unwrap()
350                                .to_string_lossy()
351                                .to_string();
352                            fs::read(fixture_path(&filename)).unwrap()
353                        },
354                    ),
355                );
356
357        let handle = tokio::runtime::Handle::current();
358        let _download_override = set_test_download_override(move |url| {
359            let uri = request_uri_from_url(url)?;
360            let request = Request::builder()
361                .method(Method::GET)
362                .uri(&uri)
363                .body(Body::empty())
364                .with_context(|| {
365                    format!(
366                        "Failed to build in-process CRLite request for {uri}"
367                    )
368                })?;
369
370            let (status, body) = handle.block_on(async {
371                let response = mirror.clone().oneshot(request).await.map_err(|error| {
372                    anyhow::anyhow!(
373                        "In-process CRLite mirror request failed for {uri}: {error}"
374                    )
375                })?;
376                let status = response.status();
377                let body = to_bytes(response.into_body(), usize::MAX)
378                    .await
379                    .with_context(|| {
380                        format!(
381                            "Failed to read in-process CRLite response body for {uri}"
382                        )
383                    })?;
384                Ok::<_, anyhow::Error>((status, body))
385            })?;
386
387            ensure!(
388                status == StatusCode::OK,
389                "In-process CRLite mirror returned {status} for {uri}: {}",
390                String::from_utf8_lossy(&body)
391            );
392
393            Ok(body.to_vec())
394        });
395
396        PcSettings {
397            server_url: MaybeValue::Value(
398                "https://ctb-test.invalid".to_string(),
399            ),
400            domain_name: MaybeOption::Value("example.com".to_string()),
401            ..Default::default()
402        }
403        .save()
404        .unwrap();
405
406        let json = get_crlite_manifest_json().await.unwrap();
407
408        assert!(json.contains("full-filter"));
409        let manifest = load_crlite_manifest().unwrap();
410        assert!(manifest.is_some());
411
412        // Verify that we can retrieve the artifact via its direct/cached path
413        let bytes_direct =
414            super::get_crlite_artifact("default/20200101-0-filter")
415                .await
416                .unwrap();
417        assert_eq!(
418            bytes_direct,
419            fs::read(fixture_path("20200101-0-filter")).unwrap()
420        );
421
422        // Verify that we can retrieve the artifact via its location/filename from the collection JSON
423        let bytes_filename = super::get_crlite_artifact("20200101-0-filter")
424            .await
425            .unwrap();
426        assert_eq!(
427            bytes_filename,
428            fs::read(fixture_path("20200101-0-filter")).unwrap()
429        );
430
431        // 1. Delete/mangle the file to check corruption detection and rate-limited refresh recovery
432        let cached_file_path = cache_dir.join("default/20200101-0-filter");
433        assert!(cached_file_path.exists());
434
435        fs::write(&cached_file_path, b"invalid mangled data").unwrap();
436
437        ctb_utilities::https::crlite::clear_in_memory_cache();
438
439        // Calling get_crlite_artifact should detect corruption, trigger a refresh and return recovered bytes
440        let bytes_recovered =
441            super::get_crlite_artifact("default/20200101-0-filter")
442                .await
443                .unwrap();
444        assert_eq!(
445            bytes_recovered,
446            fs::read(fixture_path("20200101-0-filter")).unwrap()
447        );
448
449        // Verify that the file on disk has indeed been restored to its original valid content
450        let restored_bytes = fs::read(&cached_file_path).unwrap();
451        assert_eq!(
452            restored_bytes,
453            fs::read(fixture_path("20200101-0-filter")).unwrap()
454        );
455    }
456}
457
458/*
459
460Mozilla Public License Version 2.0
461==================================
462
4631. Definitions
464--------------
465
4661.1. "Contributor"
467    means each individual or legal entity that creates, contributes to
468    the creation of, or owns Covered Software.
469
4701.2. "Contributor Version"
471    means the combination of the Contributions of others (if any) used
472    by a Contributor and that particular Contributor's Contribution.
473
4741.3. "Contribution"
475    means Covered Software of a particular Contributor.
476
4771.4. "Covered Software"
478    means Source Code Form to which the initial Contributor has attached
479    the notice in Exhibit A, the Executable Form of such Source Code
480    Form, and Modifications of such Source Code Form, in each case
481    including portions thereof.
482
4831.5. "Incompatible With Secondary Licenses"
484    means
485
486    (a) that the initial Contributor has attached the notice described
487        in Exhibit B to the Covered Software; or
488
489    (b) that the Covered Software was made available under the terms of
490        version 1.1 or earlier of the License, but not also under the
491        terms of a Secondary License.
492
4931.6. "Executable Form"
494    means any form of the work other than Source Code Form.
495
4961.7. "Larger Work"
497    means a work that combines Covered Software with other material, in
498    a separate file or files, that is not Covered Software.
499
5001.8. "License"
501    means this document.
502
5031.9. "Licensable"
504    means having the right to grant, to the maximum extent possible,
505    whether at the time of the initial grant or subsequently, any and
506    all of the rights conveyed by this License.
507
5081.10. "Modifications"
509    means any of the following:
510
511    (a) any file in Source Code Form that results from an addition to,
512        deletion from, or modification of the contents of Covered
513        Software; or
514
515    (b) any new file in Source Code Form that contains any Covered
516        Software.
517
5181.11. "Patent Claims" of a Contributor
519    means any patent claim(s), including without limitation, method,
520    process, and apparatus claims, in any patent Licensable by such
521    Contributor that would be infringed, but for the grant of the
522    License, by the making, using, selling, offering for sale, having
523    made, import, or transfer of either its Contributions or its
524    Contributor Version.
525
5261.12. "Secondary License"
527    means either the GNU General Public License, Version 2.0, the GNU
528    Lesser General Public License, Version 2.1, the GNU Affero General
529    Public License, Version 3.0, or any later versions of those
530    licenses.
531
5321.13. "Source Code Form"
533    means the form of the work preferred for making modifications.
534
5351.14. "You" (or "Your")
536    means an individual or a legal entity exercising rights under this
537    License. For legal entities, "You" includes any entity that
538    controls, is controlled by, or is under common control with You. For
539    purposes of this definition, "control" means (a) the power, direct
540    or indirect, to cause the direction or management of such entity,
541    whether by contract or otherwise, or (b) ownership of more than
542    fifty percent (50%) of the outstanding shares or beneficial
543    ownership of such entity.
544
5452. License Grants and Conditions
546--------------------------------
547
5482.1. Grants
549
550Each Contributor hereby grants You a world-wide, royalty-free,
551non-exclusive license:
552
553(a) under intellectual property rights (other than patent or trademark)
554    Licensable by such Contributor to use, reproduce, make available,
555    modify, display, perform, distribute, and otherwise exploit its
556    Contributions, either on an unmodified basis, with Modifications, or
557    as part of a Larger Work; and
558
559(b) under Patent Claims of such Contributor to make, use, sell, offer
560    for sale, have made, import, and otherwise transfer either its
561    Contributions or its Contributor Version.
562
5632.2. Effective Date
564
565The licenses granted in Section 2.1 with respect to any Contribution
566become effective for each Contribution on the date the Contributor first
567distributes such Contribution.
568
5692.3. Limitations on Grant Scope
570
571The licenses granted in this Section 2 are the only rights granted under
572this License. No additional rights or licenses will be implied from the
573distribution or licensing of Covered Software under this License.
574Notwithstanding Section 2.1(b) above, no patent license is granted by a
575Contributor:
576
577(a) for any code that a Contributor has removed from Covered Software;
578    or
579
580(b) for infringements caused by: (i) Your and any other third party's
581    modifications of Covered Software, or (ii) the combination of its
582    Contributions with other software (except as part of its Contributor
583    Version); or
584
585(c) under Patent Claims infringed by Covered Software in the absence of
586    its Contributions.
587
588This License does not grant any rights in the trademarks, service marks,
589or logos of any Contributor (except as may be necessary to comply with
590the notice requirements in Section 3.4).
591
5922.4. Subsequent Licenses
593
594No Contributor makes additional grants as a result of Your choice to
595distribute the Covered Software under a subsequent version of this
596License (see Section 10.2) or under the terms of a Secondary License (if
597permitted under the terms of Section 3.3).
598
5992.5. Representation
600
601Each Contributor represents that the Contributor believes its
602Contributions are its original creation(s) or it has sufficient rights
603to grant the rights to its Contributions conveyed by this License.
604
6052.6. Fair Use
606
607This License is not intended to limit any rights You have under
608applicable copyright doctrines of fair use, fair dealing, or other
609equivalents.
610
6112.7. Conditions
612
613Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
614in Section 2.1.
615
6163. Responsibilities
617-------------------
618
6193.1. Distribution of Source Form
620
621All distribution of Covered Software in Source Code Form, including any
622Modifications that You create or to which You contribute, must be under
623the terms of this License. You must inform recipients that the Source
624Code Form of the Covered Software is governed by the terms of this
625License, and how they can obtain a copy of this License. You may not
626attempt to alter or restrict the recipients' rights in the Source Code
627Form.
628
6293.2. Distribution of Executable Form
630
631If You distribute Covered Software in Executable Form then:
632
633(a) such Covered Software must also be made available in Source Code
634    Form, as described in Section 3.1, and You must inform recipients of
635    the Executable Form how they can obtain a copy of such Source Code
636    Form by reasonable means in a timely manner, at a charge no more
637    than the cost of distribution to the recipient; and
638
639(b) You may distribute such Executable Form under the terms of this
640    License, or sublicense it under different terms, provided that the
641    license for the Executable Form does not attempt to limit or alter
642    the recipients' rights in the Source Code Form under this License.
643
6443.3. Distribution of a Larger Work
645
646You may create and distribute a Larger Work under terms of Your choice,
647provided that You also comply with the requirements of this License for
648the Covered Software. If the Larger Work is a combination of Covered
649Software with a work governed by one or more Secondary Licenses, and the
650Covered Software is not Incompatible With Secondary Licenses, this
651License permits You to additionally distribute such Covered Software
652under the terms of such Secondary License(s), so that the recipient of
653the Larger Work may, at their option, further distribute the Covered
654Software under the terms of either this License or such Secondary
655License(s).
656
6573.4. Notices
658
659You may not remove or alter the substance of any license notices
660(including copyright notices, patent notices, disclaimers of warranty,
661or limitations of liability) contained within the Source Code Form of
662the Covered Software, except that You may alter any license notices to
663the extent required to remedy known factual inaccuracies.
664
6653.5. Application of Additional Terms
666
667You may choose to offer, and to charge a fee for, warranty, support,
668indemnity or liability obligations to one or more recipients of Covered
669Software. However, You may do so only on Your own behalf, and not on
670behalf of any Contributor. You must make it absolutely clear that any
671such warranty, support, indemnity, or liability obligation is offered by
672You alone, and You hereby agree to indemnify every Contributor for any
673liability incurred by such Contributor as a result of warranty, support,
674indemnity or liability terms You offer. You may include additional
675disclaimers of warranty and limitations of liability specific to any
676jurisdiction.
677
6784. Inability to Comply Due to Statute or Regulation
679---------------------------------------------------
680
681If it is impossible for You to comply with any of the terms of this
682License with respect to some or all of the Covered Software due to
683statute, judicial order, or regulation then You must: (a) comply with
684the terms of this License to the maximum extent possible; and (b)
685describe the limitations and the code they affect. Such description must
686be placed in a text file included with all distributions of the Covered
687Software under this License. Except to the extent prohibited by statute
688or regulation, such description must be sufficiently detailed for a
689recipient of ordinary skill to be able to understand it.
690
6915. Termination
692--------------
693
6945.1. The rights granted under this License will terminate automatically
695if You fail to comply with any of its terms. However, if You become
696compliant, then the rights granted under this License from a particular
697Contributor are reinstated (a) provisionally, unless and until such
698Contributor explicitly and finally terminates Your grants, and (b) on an
699ongoing basis, if such Contributor fails to notify You of the
700non-compliance by some reasonable means prior to 60 days after You have
701come back into compliance. Moreover, Your grants from a particular
702Contributor are reinstated on an ongoing basis if such Contributor
703notifies You of the non-compliance by some reasonable means, this is the
704first time You have received notice of non-compliance with this License
705from such Contributor, and You become compliant prior to 30 days after
706Your receipt of the notice.
707
7085.2. If You initiate litigation against any entity by asserting a patent
709infringement claim (excluding declaratory judgment actions,
710counter-claims, and cross-claims) alleging that a Contributor Version
711directly or indirectly infringes any patent, then the rights granted to
712You by any and all Contributors for the Covered Software under Section
7132.1 of this License shall terminate.
714
7155.3. In the event of termination under Sections 5.1 or 5.2 above, all
716end user license agreements (excluding distributors and resellers) which
717have been validly granted by You or Your distributors under this License
718prior to termination shall survive termination.
719
720************************************************************************
721*                                                                      *
722*  6. Disclaimer of Warranty                                           *
723*  -------------------------                                           *
724*                                                                      *
725*  Covered Software is provided under this License on an "as is"       *
726*  basis, without warranty of any kind, either expressed, implied, or  *
727*  statutory, including, without limitation, warranties that the       *
728*  Covered Software is free of defects, merchantable, fit for a        *
729*  particular purpose or non-infringing. The entire risk as to the     *
730*  quality and performance of the Covered Software is with You.        *
731*  Should any Covered Software prove defective in any respect, You     *
732*  (not any Contributor) assume the cost of any necessary servicing,   *
733*  repair, or correction. This disclaimer of warranty constitutes an   *
734*  essential part of this License. No use of any Covered Software is   *
735*  authorized under this License except under this disclaimer.         *
736*                                                                      *
737************************************************************************
738
739************************************************************************
740*                                                                      *
741*  7. Limitation of Liability                                          *
742*  --------------------------                                          *
743*                                                                      *
744*  Under no circumstances and under no legal theory, whether tort      *
745*  (including negligence), contract, or otherwise, shall any           *
746*  Contributor, or anyone who distributes Covered Software as          *
747*  permitted above, be liable to You for any direct, indirect,         *
748*  special, incidental, or consequential damages of any character      *
749*  including, without limitation, damages for lost profits, loss of    *
750*  goodwill, work stoppage, computer failure or malfunction, or any    *
751*  and all other commercial damages or losses, even if such party      *
752*  shall have been informed of the possibility of such damages. This   *
753*  limitation of liability shall not apply to liability for death or   *
754*  personal injury resulting from such party's negligence to the       *
755*  extent applicable law prohibits such limitation. Some               *
756*  jurisdictions do not allow the exclusion or limitation of           *
757*  incidental or consequential damages, so this exclusion and          *
758*  limitation may not apply to You.                                    *
759*                                                                      *
760************************************************************************
761
7628. Litigation
763-------------
764
765Any litigation relating to this License may be brought only in the
766courts of a jurisdiction where the defendant maintains its principal
767place of business and such litigation shall be governed by laws of that
768jurisdiction, without reference to its conflict-of-law provisions.
769Nothing in this Section shall prevent a party's ability to bring
770cross-claims or counter-claims.
771
7729. Miscellaneous
773----------------
774
775This License represents the complete agreement concerning the subject
776matter hereof. If any provision of this License is held to be
777unenforceable, such provision shall be reformed only to the extent
778necessary to make it enforceable. Any law or regulation which provides
779that the language of a contract shall be construed against the drafter
780shall not be used to construe this License against a Contributor.
781
78210. Versions of the License
783---------------------------
784
78510.1. New Versions
786
787Mozilla Foundation is the license steward. Except as provided in Section
78810.3, no one other than the license steward has the right to modify or
789publish new versions of this License. Each version will be given a
790distinguishing version number.
791
79210.2. Effect of New Versions
793
794You may distribute the Covered Software under the terms of the version
795of the License under which You originally received the Covered Software,
796or under the terms of any subsequent version published by the license
797steward.
798
79910.3. Modified Versions
800
801If you create software not governed by this License, and you want to
802create a new license for such software, you may create and use a
803modified version of this License if you rename the license and remove
804any references to the name of the license steward (except to note that
805such modified license differs from this License).
806
80710.4. Distributing Source Code Form that is Incompatible With Secondary
808Licenses
809
810If You choose to distribute Source Code Form that is Incompatible With
811Secondary Licenses under the terms of this version of the License, the
812notice described in Exhibit B of this License must be attached.
813
814Exhibit A - Source Code Form License Notice
815-------------------------------------------
816
817  This Source Code Form is subject to the terms of the Mozilla Public
818  License, v. 2.0. If a copy of the MPL was not distributed with this
819  file, You can obtain one at http://mozilla.org/MPL/2.0/.
820
821If it is not possible or desirable to put the notice in a particular
822file, then You may include the notice in a location (such as a LICENSE
823file in a relevant directory) where a recipient would be likely to look
824for such a notice.
825
826You may add additional accurate notices of copyright ownership.
827
828Exhibit B - "Incompatible With Secondary Licenses" Notice
829---------------------------------------------------------
830
831  This Source Code Form is "Incompatible With Secondary Licenses", as
832  defined by the Mozilla Public License, v. 2.0.
833
834*/