summaryrefslogtreecommitdiffstats
path: root/tools/crashreporter/system-symbols/mac/get_update_packages.py
blob: 3192fa3ef009cad86d91955e1c7d4af33697db80 (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
#!/usr/bin/env python

# Copyright (c) 2015 Ted Mielczarek <ted@mielczarek.org>
# and Michael R. Miller <michaelrmmiller@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import argparse
import concurrent.futures
import logging
import os
import re
import shutil
import subprocess
import tempfile

import requests
import urlparse
from PackageSymbolDumper import find_packages, process_packages

OSX_RE = re.compile(r"10\.[0-9]+\.[0-9]+")


def extract_dmg(dmg_path, dest):
    logging.info("extract_dmg({}, {})".format(dmg_path, dest))
    with tempfile.NamedTemporaryFile() as f:
        subprocess.check_call(
            ["dmg", "extract", dmg_path, f.name], stdout=subprocess.DEVNULL
        )
        subprocess.check_call(["hfsplus", f.name, "extractall"], cwd=dest)


def get_update_packages():
    for i in range(16):
        logging.info("get_update_packages: page " + str(i))
        url = (
            "https://km.support.apple.com/kb/index?page=downloads_browse&sort=recency"
            "&facet=all&category=PF6&locale=en_US&offset=%d" % i
        )
        res = requests.get(url)
        if res.status_code != 200:
            break
        data = res.json()
        downloads = data.get("downloads", [])
        if not downloads:
            break
        for d in downloads:
            title = d.get("title", "")
            if OSX_RE.search(title) and "Combo" not in title:
                logging.info("Title: " + title)
                if "fileurl" in d:
                    yield d["fileurl"]
                else:
                    logging.warn("No fileurl in download!")


def fetch_url_to_file(url, download_dir):
    filename = os.path.basename(urlparse.urlsplit(url).path)
    local_filename = os.path.join(download_dir, filename)
    if os.path.isfile(local_filename):
        logging.info("{} already exists, skipping".format(local_filename))
        return None
    r = requests.get(url, stream=True)
    res_len = int(r.headers.get("content-length", "0"))
    logging.info("Downloading {} -> {} ({} bytes)".format(url, local_filename, res_len))
    with open(local_filename, "wb") as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)
    return local_filename


def fetch_and_extract_dmg(url, tmpdir):
    logging.info("fetch_and_extract_dmg: " + url)
    filename = fetch_url_to_file(url, tmpdir)
    if not filename:
        return []
    # Extract dmg contents to a subdir
    subdir = tempfile.mkdtemp(dir=tmpdir)
    extract_dmg(filename, subdir)
    packages = list(find_packages(subdir))
    logging.info(
        "fetch_and_extract_dmg({}): found packages: {}".format(url, str(packages))
    )
    return packages


def find_update_packages(tmpdir):
    logging.info("find_update_packages")
    # Only download 2 packages at a time.
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        jobs = dict(
            (executor.submit(fetch_and_extract_dmg, url, tmpdir), url)
            for url in get_update_packages()
        )
        for future in concurrent.futures.as_completed(jobs):
            url = jobs[future]
            if future.exception() is not None:
                logging.error(
                    "exception downloading {}: {}".format(url, future.exception())
                )
            else:
                for pkg in future.result():
                    yield pkg


def main():
    parser = argparse.ArgumentParser(
        description="Download OS X update packages and dump symbols from them"
    )
    parser.add_argument(
        "--dump_syms",
        default="dump_syms",
        type=str,
        help="path to the Breakpad dump_syms executable",
    )
    parser.add_argument("to", type=str, help="destination path for the symbols")
    args = parser.parse_args()
    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    )
    for p in ("requests.packages.urllib3.connectionpool", "urllib3"):
        urllib3_logger = logging.getLogger(p)
        urllib3_logger.setLevel(logging.ERROR)
    try:
        tmpdir = tempfile.mkdtemp(suffix=".osxupdates")

        def finder():
            return find_update_packages(tmpdir)

        process_packages(finder, args.to, None, args.dump_syms)
    finally:
        shutil.rmtree(tmpdir)


if __name__ == "__main__":
    main()