aboutsummaryrefslogtreecommitdiffstats
path: root/recipes/iphone/iphone-sources
blob: 0081d4cff498628a44d2b465e96c98e2ce434ac2 (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
403
404
405
406
407
408
409
410
411
412
413
#!/usr/bin/python
#
# Download Apple sources and prepare them for OpenEmbedded.
#
# You need the following on your system to run this script:
#
#  python
#  python-beautifulsoup
#  libssl-dev
#  sudo (to mount HFS+ images)
#
# Version: 0.4

import cookielib
import os
import re
import subprocess
import shutil
import sys
import urllib
import urllib2
import urlparse
from BeautifulSoup import BeautifulSoup
import Cookie
try:
    import xml.etree.cElementTree as ET
except:
    import cElementTree as ET

DOWNLOAD_DIR = "downloads"
MOUNT_DIR = "mnt"
OUTPUT_DIR = "files"
TEMP_DIR = "tmp"
TOOLS_DIR = "tools"

class CustomCookieHandler(urllib2.BaseHandler):
    """
    Custom handler for cookies, as for some reason HTTPCookieProcessor
    has issues parsing the cookies received from Apple.
    """
    def __init__(self):
        self.cookiejar = Cookie.SimpleCookie()

    def http_request(self, request):
        # add cookies
        attrs = []
        for key in self.cookiejar:
            attrs.append( key + "=" + self.cookiejar[key].value)
        if len(attrs):
            if not request.has_header("Cookie"):
                request.add_unredirected_header(
                    "Cookie", "; ".join(attrs))
        return request

    def http_response(self, request, response):
        # store cookies
        cookie = response.info().getheader('set-cookie')
        if cookie:
            self.cookiejar.load(cookie)

        return response

    https_request = http_request
    https_response = http_response

def plist_value(e):
    """
    Convert an XML element into its python representation.
    """
    if e.tag == "integer":
        return int(e.text)
    elif e.tag == "string":
        return e.text
    elif e.tag == "array":
        return [ plist_value(c) for c in e.getchildren() ]
    elif e.tag == "dict":
        key = None
        val = {}
        for c in e.getchildren():
            if c.tag == "key":
                key = c.text
            else:
                val[key] = plist_value(c)
        return val
    else:
        raise Exception("Could not parse dict entry %s" % e)

def plist_to_hash(plist_string):
    """
    Convert the contents of an Apple .plist file to a hash.
    """
    return plist_value(ET.fromstring(plist_string).find('dict'))

def extract_pkg(pkg, dest):
    print "Extracting package %s to %s" % (pkg, dest)
    if os.system("cd %s && xar -xf %s Payload && zcat Payload | cpio -id && rm Payload" % (dest, os.path.abspath(pkg))):
        raise Exception("Could not extract package")

def mount_dmg(dmg, mnt):
    """
    Convert a DMG image to an HFS+ image then mount it.

    NOTE: requires sudo access
    """
    img = os.path.join(TEMP_DIR, os.path.basename(dmg).replace(".dmg", ".img"))

    # Check image is not mounted
    if not os.path.exists(mnt):
        os.mkdir(mnt)

    # Convert image
    if not os.path.exists(img):
        print "Converting image %s to %s " % (dmg, img)
    	if os.system("%s -i %s -o %s" % (os.path.join(TOOLS_DIR, "dmg2img"), dmg, img)):
            raise Exception("Could not convert image")

    # Mount image
    print "Mounting image %s on %s" % (img, mnt)
    if os.system("sudo mount -t hfsplus -o loop %s %s" % (img, mnt)):
        raise Exception("Could not mount image")

    return img

def umount_dmg(dmg, mnt):
    """
    Unmount a DMG image.

    NOTE: requires sudo access
    """
    img = os.path.join(TEMP_DIR, os.path.basename(dmg).replace(".dmg", ".img"))
    print "Unmounting %s" % (mnt)
    if os.system("sudo umount %s" % mnt):
        raise Exception("Could not unmount image")
    os.remove(img)

def pagetype(page):
     return page.info().getheader('content-type').split(';')[0]

def request(url, data=None):
    """
    Wrapper around urllibs2.urlopen to handle Apple's authentication form.
    """
    page = urllib2.urlopen(url, data)

    if page.geturl() != url:
        # check for connect form
        soup = BeautifulSoup(page)
        form = soup.find("form", {"name": "appleConnectForm"})
        if form:
            login_url = urlparse.urljoin(page.geturl(), form['action'])

            # log in
            print "* Logging into %s" % login_url
            page = urllib2.urlopen(urllib2.Request(login_url, data=urllib.urlencode({
                'theAccountName': apple_id,
                'theAccountPW': apple_password, 
                'theAuxValue': '',
                '1.Continue.x': '1',
                '1.Continue.y': '1'}),
                headers={'Referer': page.geturl()}))

    # follow refresh
    while pagetype(page) == "text/html":
        soup = BeautifulSoup(page)
        meta = soup.find('meta', {'http-equiv': 'REFRESH'})
        if not meta:
            break

        refresh_url = meta['content'].split(';',1)[1].split("=",1)[1]
        print "* Following refresh to %s" % refresh_url
        page = urllib2.urlopen(urllib2.Request(refresh_url, data=data, headers={'Referer': page.geturl()}))

    return page

def download(url, dest):
    """
    Download a file to a directory.
    """
    tempname = os.path.join(TEMP_DIR, os.path.basename(url)) + ".part"
    filename = os.path.join(dest, os.path.basename(url))
    if os.path.exists(filename):
        print "* Not downloading %s" % url
        return filename

    print "* Downloading %s" % url
    page = request(url)
    size = page.info().getheader('content-length')
    if pagetype(page) == "text/html":
        raise Exception("We got an HTML page, download failed")

    done = 0
    output = open(tempname, 'wb')
    sys.stdout.write("\r* Receiving..")
    sys.stdout.flush()
    while True:
        data = page.read(100000)
        if data:
            done += len(data)
            if size:
                sys.stdout.write("\r* Received %i bytes (%f %%)" % (done, float(done * 100) / float(size)))
            else:
                sys.stdout.write("\r* Received %i bytes (unknown)" % done)
            sys.stdout.flush()
            output.write(data)
        else:
            sys.stdout.write("\n")
            break
    output.close()

    shutil.move(tempname, filename)
    return filename
 
def build_tools(url, binaries):
    """
    Build DMG handling tools.
    """
    print "[ Building tools ]"
    done = True
    for bin in binaries:
        tool = os.path.join(TOOLS_DIR, bin)
        if not os.path.exists(tool):
            print "* Tool %s is missing" % bin
            done = False
    
    if done:
        print "* Tools already built"
        return

    # download and extract tools
    workdir = os.path.join(TEMP_DIR, "tools")
    if os.path.exists(workdir):
        shutil.rmtree(workdir)
    os.mkdir(workdir)
    tarball = download(url, TEMP_DIR)
    if os.system("tar -C %s --strip-components=1 -xf %s" % (workdir, tarball)):
        raise Exception("Could not extract tarball")

    # build tools
    if os.system("make -C %s" % workdir):
        raise Exception("Could not build tools")
    for bin in binaries:
        shutil.move(os.path.join(workdir, bin), os.path.join(TOOLS_DIR, bin))

    # cleanup
    shutil.rmtree(workdir)
    os.remove(tarball)
   
def get_darwin_sources(urls):
    """
    Download the source .tar.gz of Darwin opensource components.
    """
    print "[ Darwin sources ]"
    for url in urls:
        download(url, OUTPUT_DIR)

def get_firmware_key(firmware_version, firmware_build):
    """
    Return the key for a given firmware by parsing the iPhone wiki.
    """
    page = urllib2.urlopen('http://www.theiphonewiki.com/wiki/index.php?title=VFDecrypt_Keys:_2.x')
    soup = BeautifulSoup(page)

    for title in soup.findAll('span', {'class': 'mw-headline'}):
        v = title.contents[0].strip()
        if v.startswith(firmware_version) and v.count("(Build %s)" % firmware_build):
            p = title.parent.findNextSibling('p')
            return p.contents[0].strip().upper()

    return None

def generate_iphone_rootfs(url, exclude):
    """
    Generate a .tar.bz2 for the iPhone rootfs.
    """
    print "[ iPhone rootfs ]"
    ipsw = download(url, DOWNLOAD_DIR)

    # Get image contents
    plist = plist_to_hash(subprocess.Popen(["unzip", "-p", ipsw, "Restore.plist"], stdout=subprocess.PIPE).communicate()[0])

    tarname = "iphone-rootfs-%s" % plist['ProductVersion']
    workdir = os.path.join(TEMP_DIR, tarname)
    tarball = os.path.join(OUTPUT_DIR, tarname + ".tar.bz2")
    tartemp = os.path.join(TEMP_DIR, tarname + ".tar.bz2")
    imagename = plist['SystemRestoreImages']['User']
    image = os.path.join(TEMP_DIR, imagename)

    if os.path.exists(tarball):
        print "Skipping %s" % tarball
        return

    for i in ['ProductType', 'ProductVersion', 'ProductBuildVersion']:
        print "\t%s: %s" % (i, plist[i]) 

    # Get firmware key
    print "Fetching decryption key for %s" % image 
    key = get_firmware_key(plist['ProductVersion'], plist['ProductBuildVersion'])
    if not key:
        raise Exception("Could not get decryption key for firmware")
    print "Got decryption key %s" % key

    # Get dmg
    if not os.path.exists(image):
        # Extract
        print "Extracting %s" % image
        os.system("unzip %s %s -d %s" % (ipsw, imagename, TEMP_DIR))

        # Decrypt
        temp = image + ".decrypted"
        if os.system("%s -k %s -i %s -o %s" % (os.path.join(TOOLS_DIR, "vfdecrypt"), key, image, temp)):
            raise Exception("Could not decrypt image")
        os.remove(image)
        os.rename(temp, image)

    # Generate tarball
    os.mkdir(workdir)
    mount_dmg(image, workdir)

    print "Generating %s" % tarball
    excludes = " ".join([ "--exclude %s/%s" % (tarname, x) for x in exclude ])
    if os.system("tar %s --hard-dereference -C %s -cjf %s %s" % (excludes, TEMP_DIR, tartemp, tarname)):
        raise Exception("Could not create tarball")
    shutil.move(tartemp, tarball)

    umount_dmg(image, workdir)
    os.rmdir(workdir)
    os.remove(image)
    return tarball

def generate_iphone_sdk(url, iphone_version, macosx_version):
    """
    Generate a .tar.bz2 for the iPhone SDKs.
    """
    print "[ iPhone SDKs ]"
    #request('http://developer.apple.com/iphone/login.action')
    image = download(url, DOWNLOAD_DIR)

    tarname = "iphone-sdks-%s" % iphone_version
    workdir = os.path.join(TEMP_DIR, tarname)
    tarball = os.path.join(OUTPUT_DIR, tarname + ".tar.bz2")
    tartemp = os.path.join(TEMP_DIR, tarname + ".tar.bz2")

    if os.path.exists(tarball):
        print "Skipping %s" % tarball
        return

    # Cleanup
    if os.path.exists(workdir):
        shutil.rmtree(workdir)

    # Mount image
    mount_dmg(image, MOUNT_DIR)
    os.mkdir(workdir)

    # Extract iPhone stuff
    sdk = "iPhoneOS%s.sdk" % iphone_version
    tmpdir = os.path.join(TEMP_DIR, sdk)
    os.mkdir(tmpdir)
    extract_pkg("%s/Packages/iPhoneSDKHeadersAndLibs.pkg" % MOUNT_DIR, tmpdir)
    shutil.move("%s/Platforms/iPhoneOS.platform/Developer/SDKs/%s" % (tmpdir, sdk), os.path.join(workdir, sdk))
    shutil.rmtree(tmpdir)

    # Extract MacOS stuff
    sdk = "MacOSX%s.sdk" % macosx_version
    tmpdir = os.path.join(TEMP_DIR, sdk)
    os.mkdir(tmpdir)
    extract_pkg("%s/Packages/MacOSX%s.pkg" % (MOUNT_DIR, macosx_version), tmpdir)
    shutil.move("%s/SDKs/%s" % (tmpdir, sdk), os.path.join(workdir, sdk))
    shutil.rmtree(tmpdir)

    # Unmount image
    umount_dmg(image, MOUNT_DIR)

    print "Generating %s" % tarball
    if os.system("tar -C %s -cjf %s %s" % (TEMP_DIR, tartemp, tarname)):
        raise Exception("Could not create tarball")
    shutil.move(tartemp, tarball)
    shutil.rmtree(workdir)

    return tarball

if __name__ == "__main__":
    # Check arguments
    if len(sys.argv) < 4:
        print """Usage: iphone-sources <manifest> <apple_id> <apple_password>"""
        sys.exit(1)
    cmd = sys.argv[1]

    # Initialise directories
    for d in [DOWNLOAD_DIR, OUTPUT_DIR, MOUNT_DIR, TEMP_DIR, TOOLS_DIR]:
        if not os.path.exists(d):
            print "Creating %s" % d
            os.mkdir(d)

    # Read manifest
    manifest = eval(file(sys.argv[1]).read())
    apple_id = sys.argv[2]
    apple_password = sys.argv[3]

    # Register cookies
    opener = urllib2.build_opener(CustomCookieHandler())
    urllib2.install_opener(opener)

    # Perform all build steps
    build_tools(manifest['tools']['url'], manifest['tools']['binaries'])
    get_darwin_sources(manifest['sources'])
    generate_iphone_rootfs(manifest['firmware']['url'], manifest['firmware']['exclude'])
    generate_iphone_sdk(manifest['sdk']['url'], manifest['firmware']['version'], manifest['macosx']['version'])

    # Cleanup
    for d in [MOUNT_DIR, TEMP_DIR]:
        os.rmdir(d)