Compare commits
432
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ebfd397fd | ||
|
|
7dffc4b143 | ||
|
|
37cd028730 | ||
|
|
cc8993e6e7 | ||
|
|
a0b35f490b | ||
|
|
ed0614d8cf | ||
|
|
ea70eb937a | ||
|
|
b5ecff7e03 | ||
|
|
8589cbedbb | ||
|
|
edc604bfec | ||
|
|
8995e0faeb | ||
|
|
67a68bef8c | ||
|
|
7c4b43d2d1 | ||
|
|
694f96abec | ||
|
|
369854b103 | ||
|
|
104ebb9442 | ||
|
|
e1f56bfdc6 | ||
|
|
4a50411246 | ||
|
|
fc3ce8158c | ||
|
|
6e1e11809e | ||
|
|
9d67b82d5c | ||
|
|
09a3b74f93 | ||
|
|
c108f4aac4 | ||
|
|
0ac595efd9 | ||
|
|
ce1b59c1cf | ||
|
|
f7438e91b3 | ||
|
|
656d2cdd29 | ||
|
|
d8a244dd1a | ||
|
|
2dea99045d | ||
|
|
483eb38d73 | ||
|
|
475c50a8e3 | ||
|
|
4384ccb485 | ||
|
|
4b4bb7c87c | ||
|
|
cd6ccb9c7b | ||
|
|
0c91d7fe9c | ||
|
|
0d8fe0f642 | ||
|
|
b6f4e70731 | ||
|
|
efd944e337 | ||
|
|
cc86db04e2 | ||
|
|
c9ce161632 | ||
|
|
f924fc3023 | ||
|
|
5bfd32eeae | ||
|
|
7c365d304f | ||
|
|
a6a782aefb | ||
|
|
aa72c42c3b | ||
|
|
bee2be5dfb | ||
|
|
9bcc86be72 | ||
|
|
d0c932a90d | ||
|
|
4a0aa59d25 | ||
|
|
70a838c834 | ||
|
|
19dc11c735 | ||
|
|
87e854e8d4 | ||
|
|
5640bbe863 | ||
|
|
843ee9fa22 | ||
|
|
95ce084ddd | ||
|
|
ed92f6aad2 | ||
|
|
56f52ccfe4 | ||
|
|
2cc8a7d4ab | ||
|
|
0026cef7bf | ||
|
|
f0fee4a4e8 | ||
|
|
1898bbde62 | ||
|
|
031a7cd850 | ||
|
|
27f7777ba5 | ||
|
|
8caa2fa200 | ||
|
|
2fe45e940f | ||
|
|
e50720470c | ||
|
|
cebf4a85d6 | ||
|
|
5f96d1e565 | ||
|
|
1f3e0ccbe5 | ||
|
|
6252f3dbda | ||
|
|
1e71daa4f7 | ||
|
|
8eb2517d6b | ||
|
|
46e044726f | ||
|
|
b30ee65933 | ||
|
|
ae89c0a1f6 | ||
|
|
54f765b19e | ||
|
|
d8a1185c6b | ||
|
|
dbf430683f | ||
|
|
d0634fc8e6 | ||
|
|
178648f373 | ||
|
|
3a4428cfb3 | ||
|
|
dab5bf2892 | ||
|
|
e3aa7a6767 | ||
|
|
0c8394f6f4 | ||
|
|
6779322eea | ||
|
|
5d8ffc9070 | ||
|
|
72345d4c18 | ||
|
|
52a6dc2fd2 | ||
|
|
5b05c23877 | ||
|
|
81c0841201 | ||
|
|
747e183b98 | ||
|
|
62a39671fc | ||
|
|
3be9c89f49 | ||
|
|
ceb4f34827 | ||
|
|
22e785a637 | ||
|
|
221519e3ad | ||
|
|
7faed9ec18 | ||
|
|
c74ecf9c07 | ||
|
|
04233f8f7c | ||
|
|
378e3891bf | ||
|
|
9e040347f5 | ||
|
|
c99ce7dfbb | ||
|
|
6b017d5d3f | ||
|
|
b1f4ecf615 | ||
|
|
fd29bc392f | ||
|
|
61b5ceb1cb | ||
|
|
38a8914b55 | ||
|
|
ede35f29d8 | ||
|
|
7e8abd13c4 | ||
|
|
d776817d8d | ||
|
|
82d79b65c3 | ||
|
|
8cf49c6fef | ||
|
|
caba5b81af | ||
|
|
98efd568df | ||
|
|
0e729b3725 | ||
|
|
190ac7a2b0 | ||
|
|
7e91d04b28 | ||
|
|
c43df8037b | ||
|
|
5471b65a4a | ||
|
|
37d3b3f802 | ||
|
|
bd9abf504d | ||
|
|
f415391772 | ||
|
|
c29fee075d | ||
|
|
bcd5433733 | ||
|
|
c0df5b1d57 | ||
|
|
f61a35ab42 | ||
|
|
0575de80c6 | ||
|
|
2a60c9c0f3 | ||
|
|
d9fe18f95e | ||
|
|
c7ea0aedb8 | ||
|
|
f340c9cb41 | ||
|
|
8babde1e71 | ||
|
|
e5685ac806 | ||
|
|
7597115f53 | ||
|
|
8a4a52fb2c | ||
|
|
775afe32c9 | ||
|
|
c4d487ea41 | ||
|
|
23d4e3e3ce | ||
|
|
3e6d0bf55c | ||
|
|
446ebb4501 | ||
|
|
656f742bee | ||
|
|
f91f53c545 | ||
|
|
4a8004be83 | ||
|
|
970343b9ee | ||
|
|
70dc382f8d | ||
|
|
c53a20d4de | ||
|
|
3a462922f4 | ||
|
|
38840a492e | ||
|
|
70ace5c15b | ||
|
|
6ef1b62d44 | ||
|
|
3b9e8e6243 | ||
|
|
21ffa5a45a | ||
|
|
55e4c5c42e | ||
|
|
38cd714fd2 | ||
|
|
dd69adc9ff | ||
|
|
cb07313ca7 | ||
|
|
ef930ca242 | ||
|
|
f30b68945c | ||
|
|
31c0abff54 | ||
|
|
4ca24da5ea | ||
|
|
43a7614322 | ||
|
|
453b8697f9 | ||
|
|
693d513354 | ||
|
|
9488a4cd12 | ||
|
|
a9ea214d11 | ||
|
|
6d91340ffa | ||
|
|
e8851b59bc | ||
|
|
9539744417 | ||
|
|
19b011bee5 | ||
|
|
6ca74dc2c7 | ||
|
|
cb2d4ecfd2 | ||
|
|
81c8b56e52 | ||
|
|
d0b18ef3a4 | ||
|
|
b3a0f3d92d | ||
|
|
c245afac29 | ||
|
|
106e95b41f | ||
|
|
3a7ec986bc | ||
|
|
71ab28ba2b | ||
|
|
fd804f1fe3 | ||
|
|
f70a22bf63 | ||
|
|
c79655b4ed | ||
|
|
1db8f6d2cb | ||
|
|
5d79ef8157 | ||
|
|
64d1fd3e16 | ||
|
|
6e2819c643 | ||
|
|
3f2ba95276 | ||
|
|
b209180b29 | ||
|
|
b407f94610 | ||
|
|
216bb7c14e | ||
|
|
ecd0a90a22 | ||
|
|
7c5b3250a2 | ||
|
|
34f4db9151 | ||
|
|
c609d67bf5 | ||
|
|
df352a1797 | ||
|
|
9df71c5e0f | ||
|
|
a783128701 | ||
|
|
74c652cb30 | ||
|
|
2c4ef50bde | ||
|
|
92bc6103b5 | ||
|
|
ba4fcc3e20 | ||
|
|
cc202d0648 | ||
|
|
ffc64bbb70 | ||
|
|
bc506173ab | ||
|
|
29ac9bf8b6 | ||
|
|
9c8117c12d | ||
|
|
380d42f454 | ||
|
|
f1eb83674f | ||
|
|
9b55db7077 | ||
|
|
088c06087f | ||
|
|
763efbb0c2 | ||
|
|
8548dbcf3f | ||
|
|
5b4bfa8a12 | ||
|
|
4ac47f3feb | ||
|
|
1fcfee2d62 | ||
|
|
ca1b58764d | ||
|
|
9ace4fab90 | ||
|
|
37602d63cf | ||
|
|
72b2c6b351 | ||
|
|
01d9c026a5 | ||
|
|
d8aea5a8be | ||
|
|
45c3dffa98 | ||
|
|
e33a715f0a | ||
|
|
4cae85f5ec | ||
|
|
24c38be4f7 | ||
|
|
c7ae200e0d | ||
|
|
e98559dcab | ||
|
|
ca100f1e09 | ||
|
|
e448634a90 | ||
|
|
3e7d0fcb61 | ||
|
|
e344702928 | ||
|
|
1bdd03348f | ||
|
|
b482f33d2c | ||
|
|
2c86404be6 | ||
|
|
538e6a3cc7 | ||
|
|
f84f75ed8b | ||
|
|
aa9c607cba | ||
|
|
d26a1743ea | ||
|
|
ea29a85f91 | ||
|
|
07d861ee77 | ||
|
|
a55be876af | ||
|
|
244735cd93 | ||
|
|
e1cc5c9785 | ||
|
|
f976e3ef41 | ||
|
|
355730583b | ||
|
|
2701b1ed3a | ||
|
|
3e96285115 | ||
|
|
4e4d1dd107 | ||
|
|
c7915326d9 | ||
|
|
e10877e30e | ||
|
|
92f98ac82c | ||
|
|
a079880b18 | ||
|
|
2b5b52a551 | ||
|
|
ce0d740bc5 | ||
|
|
0939c6d331 | ||
|
|
d8d5021d7f | ||
|
|
6e6fc6b135 | ||
|
|
be9e933570 | ||
|
|
1d1e8fbd7b | ||
|
|
0370434afa | ||
|
|
9af227eb87 | ||
|
|
48b99d7af3 | ||
|
|
ca89eba391 | ||
|
|
474efc80c3 | ||
|
|
35dbedaa90 | ||
|
|
8f4eaca994 | ||
|
|
38950afee0 | ||
|
|
d0362eea95 | ||
|
|
d7e8f063b5 | ||
|
|
6c744d6147 | ||
|
|
5663b6f1da | ||
|
|
59612461ff | ||
|
|
c443572a72 | ||
|
|
5845e018fb | ||
|
|
9ece097efb | ||
|
|
220fc8b0ba | ||
|
|
2cf1badb11 | ||
|
|
1b66944219 | ||
|
|
1f4a2c69fa | ||
|
|
36e0531218 | ||
|
|
77aec66456 | ||
|
|
e8523fd74d | ||
|
|
767892c788 | ||
|
|
34e37569d7 | ||
|
|
4c93cb4508 | ||
|
|
431224c788 | ||
|
|
ea8f805825 | ||
|
|
7bb4c131e1 | ||
|
|
3fb7cf58d1 | ||
|
|
98ac354419 | ||
|
|
0f35931a69 | ||
|
|
3f0d7558e1 | ||
|
|
928f557782 | ||
|
|
372a7d783a | ||
|
|
b85e03fbe9 | ||
|
|
48455f1ee4 | ||
|
|
1de5029226 | ||
|
|
14f6b2f840 | ||
|
|
807d812011 | ||
|
|
d9dcd6984b | ||
|
|
6dc7e9b199 | ||
|
|
d3a53088b7 | ||
|
|
337a10604b | ||
|
|
ddd5c3d1e2 | ||
|
|
bc382530c8 | ||
|
|
f7000a05cd | ||
|
|
ec8f376fe9 | ||
|
|
8133dd8b4b | ||
|
|
d1e38b4c83 | ||
|
|
11e55547cd | ||
|
|
c1410d93b6 | ||
|
|
2b33ac168c | ||
|
|
20ca9a0c7c | ||
|
|
2ddf719dc6 | ||
|
|
33edaff22e | ||
|
|
ff1b155071 | ||
|
|
1739d0fa24 | ||
|
|
07a3ab75da | ||
|
|
ad29c492db | ||
|
|
b340b356b3 | ||
|
|
5cd5fdb2ed | ||
|
|
aa545ed419 | ||
|
|
3d507a58a6 | ||
|
|
e6d344c40a | ||
|
|
406728c066 | ||
|
|
53adc17554 | ||
|
|
0fb9ed48c9 | ||
|
|
1db648059a | ||
|
|
fccf29122d | ||
|
|
502c96a6df | ||
|
|
90a6a2fe16 | ||
|
|
c2869a05e9 | ||
|
|
aa69586334 | ||
|
|
8f3f5a5a72 | ||
|
|
f48ccd2a21 | ||
|
|
e21fd640b9 | ||
|
|
7bb7799b17 | ||
|
|
13a35d195b | ||
|
|
0c95e0c8c4 | ||
|
|
e5c65e530f | ||
|
|
65f191ce30 | ||
|
|
7a13b894ed | ||
|
|
3d95f4276e | ||
|
|
e17262ac51 | ||
|
|
4b7cd53fb4 | ||
|
|
8eaa963033 | ||
|
|
025a5e30c0 | ||
|
|
015588055a | ||
|
|
002aa3c177 | ||
|
|
e4d7285e6c | ||
|
|
93ba301b74 | ||
|
|
7f2dc8f0e4 | ||
|
|
60232a6565 | ||
|
|
49a13566fb | ||
|
|
42f7578389 | ||
|
|
ce809e6a44 | ||
|
|
ffac048d73 | ||
|
|
9fae88e8d1 | ||
|
|
b69d560259 | ||
|
|
d227e92f3e | ||
|
|
e174e130be | ||
|
|
28e00eed97 | ||
|
|
9db94ba955 | ||
|
|
2388fa3475 | ||
|
|
9b7e0788e4 | ||
|
|
38a30e40a9 | ||
|
|
869b47a1b5 | ||
|
|
99bb3e042f | ||
|
|
5b930bcdb8 | ||
|
|
7aace7204d | ||
|
|
c42950ccc4 | ||
|
|
4782828a4d | ||
|
|
123e7fbef9 | ||
|
|
8ff5514bf1 | ||
|
|
e6d4763c47 | ||
|
|
ba6e7abe12 | ||
|
|
efbb838e09 | ||
|
|
249481c842 | ||
|
|
4062563d09 | ||
|
|
55ca2cd87b | ||
|
|
6159fe07d5 | ||
|
|
2fed661399 | ||
|
|
1a9c430aca | ||
|
|
2220774e01 | ||
|
|
77f5c72415 | ||
|
|
3bd1e41270 | ||
|
|
9b92542b9c | ||
|
|
56b08482f4 | ||
|
|
c96467f35d | ||
|
|
707678e926 | ||
|
|
c50efc62a1 | ||
|
|
e4b7973685 | ||
|
|
e4c1a33251 | ||
|
|
7ba896fdde | ||
|
|
9fa097bec6 | ||
|
|
9f8cbe17c3 | ||
|
|
6f3e933d67 | ||
|
|
516ab2af65 | ||
|
|
4d385f4a33 | ||
|
|
d5456f90f2 | ||
|
|
96772f8a07 | ||
|
|
d86a513605 | ||
|
|
12a33b5b4c | ||
|
|
6f74aa1698 | ||
|
|
4e1232e63b | ||
|
|
f50aaf807a | ||
|
|
63f3b3eaae | ||
|
|
a6845ce01a | ||
|
|
e9fdbc237e | ||
|
|
e123cfa3fe | ||
|
|
affe3d3792 | ||
|
|
0b593abc10 | ||
|
|
dc43429a25 | ||
|
|
ed03d2c5aa | ||
|
|
624b6b88db | ||
|
|
20b6a9776c | ||
|
|
72d768d17d | ||
|
|
91549567e1 | ||
|
|
6e9efa0be3 | ||
|
|
8709338949 | ||
|
|
f9d6c00f60 | ||
|
|
e122927c5d | ||
|
|
43d524e186 | ||
|
|
a4dc3e4a47 | ||
|
|
e5f838463b | ||
|
|
e24d538232 | ||
|
|
9170c4d106 | ||
|
|
a93cf336b8 | ||
|
|
7bc6620b45 | ||
|
|
4f0ba2c41a | ||
|
|
cfaabf7cb0 | ||
|
|
d4cd9fa88c | ||
|
|
a7a3ddbf9c |
+21
-5
@@ -1,6 +1,22 @@
|
||||
[submodule "External/ReactiveCocoa"]
|
||||
path = External/ReactiveCocoa
|
||||
[submodule "External/OHHTTPStubs"]
|
||||
path = External/OHHTTPStubs
|
||||
url = https://github.com/github/OHHTTPStubs
|
||||
[submodule "Carthage.checkout/Nimble"]
|
||||
path = Carthage/Checkouts/Nimble
|
||||
url = https://github.com/Quick/Nimble.git
|
||||
[submodule "Carthage.checkout/ReactiveCocoa"]
|
||||
path = Carthage/Checkouts/ReactiveCocoa
|
||||
url = https://github.com/ReactiveCocoa/ReactiveCocoa.git
|
||||
[submodule "External/Mantle"]
|
||||
path = External/Mantle
|
||||
url = https://github.com/github/Mantle.git
|
||||
[submodule "Carthage.checkout/Quick"]
|
||||
path = Carthage/Checkouts/Quick
|
||||
url = https://github.com/Quick/Quick.git
|
||||
[submodule "Carthage.checkout/xcconfigs"]
|
||||
path = Carthage/Checkouts/xcconfigs
|
||||
url = https://github.com/jspahrsummers/xcconfigs.git
|
||||
[submodule "Carthage.checkout/Mantle"]
|
||||
path = Carthage/Checkouts/Mantle
|
||||
url = https://github.com/Mantle/Mantle.git
|
||||
[submodule "Carthage/Checkouts/Nimble"]
|
||||
url = https://github.com/Quick/Nimble.git
|
||||
[submodule "Carthage/Checkouts/Quick"]
|
||||
url = https://github.com/Quick/Quick.git
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
osx_image: xcode7.1
|
||||
language: objective-c
|
||||
before_install:
|
||||
- brew update
|
||||
- brew outdated xctool || brew upgrade xctool
|
||||
install: script/bootstrap
|
||||
script: script/cibuild
|
||||
notifications:
|
||||
email: false
|
||||
env:
|
||||
global:
|
||||
secure: L4C3hHzXc/sgL35dIz3kjqIzPWnXCHsFOgbOcz0f249zlnegeKHQdChm4HUDtfrbmKLMYQCIvVfcgPeLaHkCSeHqXUihXLT2LglK+0GX3MBbFzde9x1uln2O68hH1tTmBg2O2i4Dtc4D3e+2tVv3XmhQDZt0znIVO6n9YgevDqw=
|
||||
@@ -0,0 +1,2 @@
|
||||
github "Mantle/Mantle" ~> 1.5.3
|
||||
github "ReactiveCocoa/ReactiveCocoa" ~> 2.4.3
|
||||
@@ -0,0 +1,3 @@
|
||||
github "jspahrsummers/xcconfigs" >= 0.7.1
|
||||
github "Quick/Quick" ~> 0.7
|
||||
github "Quick/Nimble" ~> 2.0
|
||||
@@ -0,0 +1,5 @@
|
||||
github "Mantle/Mantle" "1.5.6"
|
||||
github "Quick/Nimble" "v2.0.0"
|
||||
github "Quick/Quick" "v0.7.0"
|
||||
github "ReactiveCocoa/ReactiveCocoa" "v2.5"
|
||||
github "jspahrsummers/xcconfigs" "0.8.1"
|
||||
+1
Submodule Carthage/Checkouts/Mantle added at e41221ee94
+1
Submodule Carthage/Checkouts/Nimble added at 20a3f3b4e6
+1
Submodule Carthage/Checkouts/Quick added at 7d0b8c2135
+1
Submodule Carthage/Checkouts/ReactiveCocoa added at 32364b9040
+1
Submodule Carthage/Checkouts/xcconfigs added at 99624a6af3
Vendored
-1
Submodule External/Mantle deleted from 6cbdbebc44
+1
Submodule External/OHHTTPStubs added at 08776e99bc
Vendored
-1
Submodule External/ReactiveCocoa deleted from c01fe91544
@@ -6,6 +6,7 @@ and transparent as updates to a website**.
|
||||
Instead of publishing a feed of versions from which your app must select,
|
||||
Squirrel updates to the version your server tells it to. This allows you to
|
||||
intelligently update your clients based on the request you give to Squirrel.
|
||||
The server can remotely drive behaviors like rolling back or phased rollouts.
|
||||
|
||||
Your request can include authentication details, custom headers or a request
|
||||
body so that your server has the context it needs in order to supply the most
|
||||
@@ -13,21 +14,49 @@ suitable update.
|
||||
|
||||
The update JSON Squirrel requests should be dynamically generated based on
|
||||
criteria in the request, and whether an update is required. Squirrel relies
|
||||
on server side support for determining whether an update is required, see [Server
|
||||
Support](#server-support) below.
|
||||
on server side support for determining whether an update is required, see
|
||||
[Server Support](#server-support).
|
||||
|
||||
Squirrel’s installer is also designed to be fault tolerant, and ensure that any
|
||||
Squirrel's installer is also designed to be fault tolerant, and ensure that any
|
||||
updates installed are valid.
|
||||
|
||||

|
||||
|
||||
# Adopting Squirrel
|
||||
|
||||
1. Install xctool with `brew install xctool`
|
||||
1. Add the Squirrel repository as a git submodule
|
||||
1. Add a reference to Squirrel.xcodeproj to your project
|
||||
1. Run `script/bootstrap` from within the submodule
|
||||
1. Add references to Squirrel.xcodeproj and its [dependencies](#dependencies) to
|
||||
your project
|
||||
1. Add Squirrel.framework as a target dependency
|
||||
1. Link Squirrel.framework and add it to a Copy Files build phase which copies
|
||||
it into your Frameworks directory
|
||||
1. Ensure your Runpath Search Paths (`LD_RUNPATH_SEARCH_PATHS`) includes the
|
||||
Frameworks directory Squirrel.framework is copied into
|
||||
1. Ensure your application includes the [dependencies](#dependencies). Squirrel
|
||||
does not embed them itself.
|
||||
|
||||
If you’re developing Squirrel on its own, then use `Squirrel.xcworkspace`.
|
||||
|
||||
# Dependencies
|
||||
|
||||
Squirrel depends on [ReactiveCocoa](http://github.com/ReactiveCocoa/ReactiveCocoa)
|
||||
and [Mantle](https://github.com/Mantle/Mantle).
|
||||
|
||||
If your application is already using ReactiveCocoa, ensure it is using the same
|
||||
version as Squirrel.
|
||||
|
||||
Otherwise, add a target dependency and Copy Files build phase entry for the
|
||||
ReactiveCocoa.framework target included in Squirrel's repository, in
|
||||
External/ReactiveCocoa.
|
||||
|
||||
Similarly, ensure your application includes Mantle, or copies in the Squirrel
|
||||
version.
|
||||
|
||||
Finally, ensure your application's Runpath Search Paths (`LD_RUNPATH_SEARCH_PATHS`)
|
||||
includes the directory that Squirrel.framework, ReactiveCocoa.framework
|
||||
and Mantle.framework are copied into.
|
||||
|
||||
# Configuration
|
||||
|
||||
Once Squirrel is added to your project, you need to configure and start it.
|
||||
|
||||
@@ -35,44 +64,102 @@ Once Squirrel is added to your project, you need to configure and start it.
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
|
||||
self.updater = [[SQRLUpdater alloc] initWithUpdateRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://mycompany.com/myapp/latest"]]];
|
||||
[self.updater startAutomaticChecksWithInterval:/* 4 Hours */ 60 * 60 * 4];
|
||||
[self.updater checkForUpdates];
|
||||
NSURLComponents *components = [[NSURLComponents alloc] init];
|
||||
|
||||
components.scheme = @"http";
|
||||
components.host = @"mycompany.com";
|
||||
components.path = @"/myapp/latest";
|
||||
|
||||
NSString *bundleVersion = NSBundle.mainBundle.sqrl_bundleVersion;
|
||||
components.query = [[NSString stringWithFormat:@"version=%@", bundleVersion] stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]
|
||||
|
||||
self.updater = [[SQRLUpdater alloc] initWithUpdateRequest:[NSURLRequest requestWithURL:components.URL]];
|
||||
|
||||
// Check for updates every 4 hours.
|
||||
[self.updater startAutomaticChecksWithInterval:60 * 60 * 4];
|
||||
}
|
||||
```
|
||||
|
||||
Squirrel will periodically request and automatically download any updates.
|
||||
Squirrel will periodically request and automatically download any updates. When
|
||||
your application terminates, any downloaded update will be automatically
|
||||
installed.
|
||||
|
||||
Before your application terminates, it should tell Squirrel to install any
|
||||
updates that it has downloaded:
|
||||
## Update Requests
|
||||
|
||||
Squirrel is indifferent to the request the client application provides for
|
||||
update checking. `Accept: application/json` is added to the request headers
|
||||
because Squirrel is responsible for parsing the response.
|
||||
|
||||
For the requirements imposed on the responses and the body format of an update
|
||||
response see [Server Support](#server-support).
|
||||
|
||||
Your update request must *at least* include a version identifier so that the
|
||||
server can determine whether an update for this specific version is required. It
|
||||
may also include other identifying criteria such as operating system version or
|
||||
username, to allow the server to deliver as fine grained an update as you
|
||||
would like.
|
||||
|
||||
How you include the version identifier or other criteria is specific to the
|
||||
server that you are requesting updates from. A common approach is to use query
|
||||
parameters, [Configuration](#configuration) shows an example of this.
|
||||
|
||||
## Update Available Notifications
|
||||
|
||||
To know when an update is ready to be installed, you can subscribe to the
|
||||
`updates` signal on `SQRLUpdater`:
|
||||
|
||||
```objc
|
||||
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
|
||||
[self.updater installUpdateIfNeeded:^(BOOL success, NSError *error) {
|
||||
if (success) {
|
||||
NSLog(@"Successfully installed an update");
|
||||
} else {
|
||||
NSLog(@"Failed to update: %@", error);
|
||||
}
|
||||
|
||||
[sender replyToApplicationShouldTerminate:YES];
|
||||
}];
|
||||
|
||||
return NSTerminateLater;
|
||||
}
|
||||
[self.updater.updates subscribeNext:^(SQRLDownloadedUpdate *downloadedUpdate) {
|
||||
NSLog(@"An update is ready to install: %@", downloadedUpdate);
|
||||
}];
|
||||
```
|
||||
|
||||
# Update JSON Format
|
||||
## Installing Updates
|
||||
|
||||
Squirrel requests the URL you provide with `Accept: application/json` and
|
||||
expects the following schema in response:
|
||||
While downloaded updates are automatically installed when your application
|
||||
terminates, if don't want to wait you can manually terminate the app to begin
|
||||
the installation process immediately.
|
||||
|
||||
Once an [update available notification](#update-available-notifications) has
|
||||
been received, you may want to present an interface informing the user about
|
||||
the update and offering the ability to install and relaunch.
|
||||
|
||||
To explicitly install a downloaded update and automatically relaunch afterward,
|
||||
subscribe to the `relaunchToInstallUpdate` signal on `SQRLUpdater`:
|
||||
|
||||
```objc
|
||||
[[self.updater relaunchToInstallUpdate] subscribeError:^(NSError *error) {
|
||||
NSLog(@"Error preparing update: %@", error);
|
||||
}];
|
||||
```
|
||||
|
||||
# Server Support
|
||||
|
||||
Your server should determine whether an update is required based on the
|
||||
[Update Request](#update-requests) your client issues.
|
||||
|
||||
If an update is required your server should respond with a status code of
|
||||
[200 OK](http://tools.ietf.org/html/rfc2616#section-10.2.1) and include the
|
||||
[update JSON](#update-json-format) in the body. Squirrel **will** download and
|
||||
install this update, even if the version of the update is the same as the
|
||||
currently running version. To save redundantly downloading the same version
|
||||
multiple times your server must not inform the client to update.
|
||||
|
||||
If no update is required your server must respond with a status code of
|
||||
[204 No Content](http://tools.ietf.org/html/rfc2616#section-10.2.5). Squirrel
|
||||
will check for an update again at the interval you specify.
|
||||
|
||||
## Update JSON Format
|
||||
|
||||
When an update is available, Squirrel expects the following schema in response
|
||||
to the update request provided:
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "http://mycompany.com/myapp/releases/myrelease",
|
||||
"name": "My Release Name",
|
||||
"notes": "Theses are some release notes innit",
|
||||
"pub_date": "2013-09-18T12:29:53+01:00",
|
||||
"pub_date": "2013-09-18T12:29:53+01:00"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -83,24 +170,10 @@ installing ZIP updates. If future update formats are supported their MIME type
|
||||
will be added to the `Accept` header so that your server can return the
|
||||
appropriate format.
|
||||
|
||||
"pub_date" if present must be formatted according to ISO 8601
|
||||
|
||||
# Server Support
|
||||
|
||||
If an update is required your server should respond with a status code of
|
||||
[200 OK](http://tools.ietf.org/html/rfc2616#section-10.2.1) and include the
|
||||
update JSON in the body. Squirrel **will** download and install this update,
|
||||
even if the version of the update is the same as the currently running version.
|
||||
To save redundantly downloading the same version multiple times your server must
|
||||
inform the client not to update.
|
||||
|
||||
If no update is required your server must respond with a status code of
|
||||
[204 No Content](http://tools.ietf.org/html/rfc2616#section-10.2.5). Squirrel
|
||||
will check for an update again at the interval you specify.
|
||||
"pub_date" if present must be formatted according to ISO 8601.
|
||||
|
||||
# User Interface
|
||||
|
||||
Squirrel does not provide an updates interface, if you want to display available
|
||||
updates, subscribe to the `SQRLUpdaterUpdateAvailableNotification` notification.
|
||||
|
||||

|
||||
Squirrel does not provide any GUI components for presenting updates. If you want
|
||||
to indicate updates to the user, make sure to [listen for downloaded
|
||||
updates](#update-available-notifications).
|
||||
|
||||
+481
-626
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0500"
|
||||
version = "1.3">
|
||||
LastUpgradeVersion = "0710"
|
||||
version = "2.0">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
@@ -22,14 +22,14 @@
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0C22BEE179CC00E00158214"
|
||||
BuildableName = "SquirrelTests.octest"
|
||||
BuildableName = "SquirrelTests.xctest"
|
||||
BlueprintName = "SquirrelTests"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
@@ -37,32 +37,61 @@
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Test">
|
||||
shouldUseLaunchSchemeArgsEnv = "NO">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0C22BEE179CC00E00158214"
|
||||
BuildableName = "SquirrelTests.octest"
|
||||
BuildableName = "SquirrelTests.xctest"
|
||||
BlueprintName = "SquirrelTests"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0C22BD6179CC00E00158214"
|
||||
BuildableName = "Squirrel.framework"
|
||||
BlueprintName = "Squirrel"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "FORCE_APP_IDENTIFIER"
|
||||
value = "com.github.Squirrel.SquirrelTests"
|
||||
isEnabled = "YES">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = ""
|
||||
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugXPCServices = "NO"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0C22BD6179CC00E00158214"
|
||||
BuildableName = "Squirrel.framework"
|
||||
BlueprintName = "Squirrel"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQRLUpdateFromURL"
|
||||
@@ -74,11 +103,20 @@
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Profile"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Profile"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0C22BD6179CC00E00158214"
|
||||
BuildableName = "Squirrel.framework"
|
||||
BlueprintName = "Squirrel"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0500"
|
||||
LastUpgradeVersion = "0710"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -23,10 +23,10 @@
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Test"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Test">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
@@ -38,17 +38,21 @@
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable>
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D08D4E0B17B451500012B22D"
|
||||
@@ -61,12 +65,13 @@
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Release"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable>
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D08D4E0B17B451500012B22D"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0500"
|
||||
LastUpgradeVersion = "0710"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -23,30 +23,42 @@
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Test"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Test">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D014AC0017B97885007D79D0"
|
||||
BuildableName = "ShipIt"
|
||||
BlueprintName = "ShipIt"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Release"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "group:Squirrel.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Carthage/Checkouts/Mantle/Mantle.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Carthage/Checkouts/ReactiveCocoa/ReactiveCocoa.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:External/OHHTTPStubs/OHHTTPStubs/OHHTTPStubs.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Carthage/Checkouts/Quick/Quick.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Carthage/Checkouts/Nimble/Nimble.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -14,4 +14,7 @@
|
||||
// Info.plist, or nil if the key is not present.
|
||||
@property (nonatomic, copy, readonly) NSString *sqrl_bundleVersion;
|
||||
|
||||
/// The value of the `kCFBundleExecutableKey` key.
|
||||
@property (nonatomic, copy, readonly) NSString *sqrl_executableName;
|
||||
|
||||
@end
|
||||
|
||||
@@ -14,4 +14,8 @@
|
||||
return [self objectForInfoDictionaryKey:(id)kCFBundleVersionKey];
|
||||
}
|
||||
|
||||
- (NSString *)sqrl_executableName {
|
||||
return [self objectForInfoDictionaryKey:(id)kCFBundleExecutableKey];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <ReactiveCocoa/RACSignal.h>
|
||||
|
||||
@interface RACSignal (SQRLTransactionExtensions)
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
//
|
||||
|
||||
#import "RACSignal+SQRLTransactionExtensions.h"
|
||||
|
||||
#import <ReactiveCocoa/RACDisposable.h>
|
||||
#import <IOKit/pwr_mgt/IOPMLib.h>
|
||||
|
||||
// How long before power assertions time out.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// SQRLAuthorization.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 06/01/2014.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import <Security/Security.h>
|
||||
|
||||
// Wraps an AuthorizationRef.
|
||||
@interface SQRLAuthorization : NSObject
|
||||
|
||||
// Designated initializer.
|
||||
//
|
||||
// authorization - Must not be NULL, the returned object assumes ownership of
|
||||
// the passed authorization.
|
||||
//
|
||||
// Returns an object which ties the `authorization` argument to the returned
|
||||
// object's lifetime.
|
||||
- (instancetype)initWithAuthorization:(AuthorizationRef)authorization;
|
||||
|
||||
@property (readonly, nonatomic, assign) AuthorizationRef authorization;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,28 @@
|
||||
//
|
||||
// SQRLAuthorization.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 06/01/2014.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLAuthorization.h"
|
||||
|
||||
@implementation SQRLAuthorization
|
||||
|
||||
- (instancetype)initWithAuthorization:(AuthorizationRef)authorization {
|
||||
NSParameterAssert(authorization != NULL);
|
||||
|
||||
self = [self init];
|
||||
if (self == nil) return nil;
|
||||
|
||||
_authorization = authorization;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
if (_authorization != NULL) AuthorizationFree(_authorization, kAuthorizationFlagDestroyRights);
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -9,34 +9,56 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Mantle/Mantle.h>
|
||||
|
||||
// The domain for errors originating within SQRLCodeSignature.
|
||||
extern NSString * const SQRLCodeSignatureErrorDomain;
|
||||
|
||||
// The bundle did not pass codesign verification.
|
||||
extern const NSInteger SQRLCodeSignatureErrorDidNotPass;
|
||||
|
||||
// A static code object could not be created for the target bundle or running
|
||||
// code.
|
||||
extern const NSInteger SQRLCodeSignatureErrorCouldNotCreateStaticCode;
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
// Implements the verification of Apple code signatures.
|
||||
// Implements the verification of Apple code signatures and requirements.
|
||||
@interface SQRLCodeSignature : MTLModel
|
||||
|
||||
// A serialized version of the `SecRequirementRef` that the receiver was
|
||||
// initialized with.
|
||||
@property (nonatomic, copy, readonly) NSData *requirementData;
|
||||
|
||||
// Determines the code signature of the currently-executing application.
|
||||
// Determines the designated requirement of the currently-executing application.
|
||||
// The returned code signature can be used to verify that a bundle is code sign
|
||||
// valid and meets the designated requirement of the current application.
|
||||
//
|
||||
// error - If not NULL, set to any error that occurs.
|
||||
//
|
||||
// Returns a `SQRLCodeSignature`, or nil if an error occurs retrieving the
|
||||
// signature for the running code.
|
||||
// designated requirement for the running code.
|
||||
+ (instancetype)currentApplicationSignature:(NSError **)error;
|
||||
|
||||
// Initializes the receiver with the given requirement.
|
||||
// Determines the designated requirement of the specified bundle. The returned
|
||||
// code signature can be used to verify that an arbitrary bundle is valid and
|
||||
// meets the designated requirement of `bundle`.
|
||||
//
|
||||
// requirement - The code requirement for tested bundles. This must not be NULL.
|
||||
- (id)initWithRequirement:(SecRequirementRef)requirement;
|
||||
// bundleURL - Must not be nil, the location of a bundle directory structure
|
||||
// which has been code signed and includes a designated requirement.
|
||||
// This bundle's designated requirement is used when verifying other
|
||||
// bundles.
|
||||
// error - If not NULL, set to any error that occurs.
|
||||
//
|
||||
// Returns a `SQRLCodeSignature`, or nil if an error occurs retrieving the
|
||||
// designated requirement of the bundle at `bundleURL`.
|
||||
+ (instancetype)signatureWithBundle:(NSURL *)bundleURL error:(NSError **)error;
|
||||
|
||||
// Verifies that the code signature of the specified bundle matches the receiver.
|
||||
// Verifies the code signature of the specified bundle and verifies that the
|
||||
// bundle meets the receiver's requirement.
|
||||
//
|
||||
// bundleURL - The URL to the bundle to verify on disk. This must not be nil.
|
||||
//
|
||||
// Returns a signal which will synchronously send completed on success, or error
|
||||
// if the code signature was not verified successfully.
|
||||
// if the requirement was not verified successfully.
|
||||
- (RACSignal *)verifyBundleAtURL:(NSURL *)bundleURL;
|
||||
|
||||
@end
|
||||
|
||||
@@ -7,17 +7,29 @@
|
||||
//
|
||||
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
|
||||
#import "EXTKeyPathCoding.h"
|
||||
#import "EXTScope.h"
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
#import <ReactiveCocoa/RACSubscriber.h>
|
||||
#import <Security/Security.h>
|
||||
#import "Squirrel-Constants.h"
|
||||
|
||||
NSString * const SQRLCodeSignatureErrorDomain = @"SQRLCodeSignatureErrorDomain";
|
||||
|
||||
const NSInteger SQRLCodeSignatureErrorDidNotPass = -1;
|
||||
const NSInteger SQRLCodeSignatureErrorCouldNotCreateStaticCode = -2;
|
||||
|
||||
@interface SQRLCodeSignature ()
|
||||
|
||||
// A `SecRequirementRef` that tested bundles must satisfy.
|
||||
@property (atomic, strong) id requirement;
|
||||
|
||||
// Initializes the receiver with the given requirement.
|
||||
//
|
||||
// This property is automatically retained.
|
||||
@property (atomic) id requirement;
|
||||
// This is the designated initializer for this class.
|
||||
//
|
||||
// requirement - The code requirement for tested bundles. This must not be NULL.
|
||||
- (id)initWithRequirement:(SecRequirementRef)requirement;
|
||||
|
||||
@end
|
||||
|
||||
@@ -33,8 +45,49 @@
|
||||
|
||||
#pragma mark Lifecycle
|
||||
|
||||
+ (instancetype)currentApplicationSignature:(NSError **)error {
|
||||
return [self modelWithDictionary:nil error:error];
|
||||
+ (instancetype)currentApplicationSignature:(NSError **)errorRef {
|
||||
SecCodeRef staticCode = NULL;
|
||||
OSStatus error = SecCodeCopySelf(kSecCSDefaultFlags, &staticCode);
|
||||
if (error != noErr) {
|
||||
if (errorRef != NULL) *errorRef = [NSError errorWithDomain:NSOSStatusErrorDomain code:error userInfo:nil];
|
||||
return nil;
|
||||
}
|
||||
|
||||
@onExit {
|
||||
CFRelease(staticCode);
|
||||
};
|
||||
|
||||
return [self signatureWithCode:staticCode error:errorRef];
|
||||
}
|
||||
|
||||
+ (instancetype)signatureWithBundle:(NSURL *)bundleURL error:(NSError **)errorRef {
|
||||
SecStaticCodeRef bundleCode = NULL;
|
||||
OSStatus error = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &bundleCode);
|
||||
if (error != noErr) {
|
||||
if (errorRef != NULL) *errorRef = [NSError errorWithDomain:NSOSStatusErrorDomain code:error userInfo:nil];
|
||||
return nil;
|
||||
}
|
||||
|
||||
@onExit {
|
||||
CFRelease(bundleCode);
|
||||
};
|
||||
|
||||
return [self signatureWithCode:bundleCode error:errorRef];
|
||||
}
|
||||
|
||||
+ (instancetype)signatureWithCode:(SecStaticCodeRef)code error:(NSError **)errorRef {
|
||||
SecRequirementRef designatedRequirement = NULL;
|
||||
OSStatus error = SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, &designatedRequirement);
|
||||
if (error != noErr) {
|
||||
if (errorRef != NULL) *errorRef = [NSError errorWithDomain:NSOSStatusErrorDomain code:error userInfo:nil];
|
||||
return nil;
|
||||
}
|
||||
|
||||
@onExit {
|
||||
CFRelease(designatedRequirement);
|
||||
};
|
||||
|
||||
return [[SQRLCodeSignature alloc] initWithRequirement:designatedRequirement];
|
||||
}
|
||||
|
||||
- (id)initWithRequirement:(SecRequirementRef)requirement {
|
||||
@@ -45,35 +98,6 @@
|
||||
} error:NULL];
|
||||
}
|
||||
|
||||
- (id)initWithDictionary:(NSDictionary *)dictionary error:(NSError **)error {
|
||||
self = [super initWithDictionary:dictionary error:error];
|
||||
if (self == nil) return nil;
|
||||
|
||||
if (self.requirement == nil) {
|
||||
SecCodeRef staticCode = NULL;
|
||||
OSStatus result = SecCodeCopySelf(kSecCSDefaultFlags, &staticCode);
|
||||
@onExit {
|
||||
if (staticCode != NULL) CFRelease(staticCode);
|
||||
};
|
||||
|
||||
if (result != noErr) {
|
||||
if (error != NULL) *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:result userInfo:nil];
|
||||
return nil;
|
||||
}
|
||||
|
||||
SecRequirementRef req = NULL;
|
||||
result = SecCodeCopyDesignatedRequirement(staticCode, kSecCSDefaultFlags, &req);
|
||||
self.requirement = CFBridgingRelease(req);
|
||||
|
||||
if (result != noErr) {
|
||||
if (error != NULL) *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:result userInfo:nil];
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark Verification
|
||||
|
||||
- (RACSignal *)verifyBundleAtURL:(NSURL *)bundleURL {
|
||||
@@ -95,7 +119,7 @@
|
||||
NSString *failureReason = CFBridgingRelease(SecCopyErrorMessageString(result, NULL));
|
||||
if (failureReason != nil) userInfo[NSLocalizedFailureReasonErrorKey] = failureReason;
|
||||
|
||||
[subscriber sendError:[NSError errorWithDomain:SQRLErrorDomain code:SQRLCodeSignatureErrorCouldNotCreateStaticCode userInfo:userInfo]];
|
||||
[subscriber sendError:[NSError errorWithDomain:SQRLCodeSignatureErrorDomain code:SQRLCodeSignatureErrorCouldNotCreateStaticCode userInfo:userInfo]];
|
||||
return nil;
|
||||
}
|
||||
|
||||
@@ -114,7 +138,7 @@
|
||||
if (failureReason != nil) userInfo[NSLocalizedFailureReasonErrorKey] = failureReason;
|
||||
if (validityError != NULL) userInfo[NSUnderlyingErrorKey] = (__bridge NSError *)validityError;
|
||||
|
||||
[subscriber sendError:[NSError errorWithDomain:SQRLErrorDomain code:SQRLCodeSignatureErrorDidNotPass userInfo:userInfo]];
|
||||
[subscriber sendError:[NSError errorWithDomain:SQRLCodeSignatureErrorDomain code:SQRLCodeSignatureErrorDidNotPass userInfo:userInfo]];
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,13 +6,16 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
// Provides the file locations that Squirrel/ShipIt use.
|
||||
@interface SQRLDirectoryManager : NSObject
|
||||
|
||||
// The application identifier to use in file locations.
|
||||
@property (nonatomic, copy, readonly) NSString *applicationIdentifier;
|
||||
|
||||
// Returns the shared `SQRLDirectoryManager` for the running application, based
|
||||
// on the bundle identifier or application name.
|
||||
+ (instancetype)currentApplicationManager;
|
||||
@@ -26,14 +29,24 @@
|
||||
// on-disk locations for. This must not be nil.
|
||||
- (instancetype)initWithApplicationIdentifier:(NSString *)appIdentifier;
|
||||
|
||||
// Finds or creates an Application Support folder.
|
||||
// Finds or creates a storage folder.
|
||||
//
|
||||
// Returns a signal which synchronously sends a URL then completes, or errors.
|
||||
- (RACSignal *)applicationSupportURL;
|
||||
- (RACSignal *)storageURL;
|
||||
|
||||
// Determines where archived `SQRLShipItState` should be saved.
|
||||
//
|
||||
// Returns a signal which synchronously sends a URL then completes, or errors.
|
||||
- (RACSignal *)shipItStateURL;
|
||||
|
||||
// Determines where ShipIt's stdout log should be saved.
|
||||
//
|
||||
// Returns a signal which synchronously sends a URL then completes, or errors.
|
||||
- (RACSignal *)shipItStdoutURL;
|
||||
|
||||
// Determines where ShipIt's stderr log should be saved.
|
||||
//
|
||||
// Returns a signal which synchronously sends a URL then completes, or errors.
|
||||
- (RACSignal *)shipItStderrURL;
|
||||
|
||||
@end
|
||||
|
||||
@@ -7,14 +7,8 @@
|
||||
//
|
||||
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
|
||||
@interface SQRLDirectoryManager ()
|
||||
|
||||
// The application identifier to use in file locations.
|
||||
@property (nonatomic, copy, readonly) NSString *applicationIdentifier;
|
||||
|
||||
@end
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
|
||||
@implementation SQRLDirectoryManager
|
||||
|
||||
@@ -30,7 +24,7 @@
|
||||
// Should only fallback to when running under otest, where
|
||||
// NSBundle.mainBundle doesn't return useful data.
|
||||
if (identifier == nil) {
|
||||
identifier = NSRunningApplication.currentApplication.localizedName;
|
||||
identifier = NSProcessInfo.processInfo.environment[@"FORCE_APP_IDENTIFIER"];
|
||||
}
|
||||
|
||||
NSAssert(identifier != nil, @"Could not automatically determine the current application's identifier");
|
||||
@@ -53,11 +47,11 @@
|
||||
|
||||
#pragma mark Folder URLs
|
||||
|
||||
- (RACSignal *)applicationSupportURL {
|
||||
- (RACSignal *)storageURL {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
NSError *error = nil;
|
||||
NSURL *folderURL = [NSFileManager.defaultManager URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
|
||||
NSURL *folderURL = [NSFileManager.defaultManager URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
|
||||
if (folderURL == nil) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
@@ -69,18 +63,36 @@
|
||||
|
||||
return [RACSignal return:folderURL];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -applicationSupportURL", self];
|
||||
setNameWithFormat:@"%@ -storageURL", self];
|
||||
}
|
||||
|
||||
- (RACSignal *)shipItStateURL {
|
||||
return [[[self
|
||||
applicationSupportURL]
|
||||
storageURL]
|
||||
map:^(NSURL *folderURL) {
|
||||
return [folderURL URLByAppendingPathComponent:@"ShipItState.plist"];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -shipItStateURL", self];
|
||||
}
|
||||
|
||||
- (RACSignal *)shipItStdoutURL {
|
||||
return [[[self
|
||||
storageURL]
|
||||
map:^(NSURL *folderURL) {
|
||||
return [folderURL URLByAppendingPathComponent:@"ShipIt_stdout.log"];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -shipItStdoutURL", self];
|
||||
}
|
||||
|
||||
- (RACSignal *)shipItStderrURL {
|
||||
return [[[self
|
||||
storageURL]
|
||||
map:^(NSURL *folderURL) {
|
||||
return [folderURL URLByAppendingPathComponent:@"ShipIt_stderr.log"];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -shipItStderrURL", self];
|
||||
}
|
||||
|
||||
#pragma mark NSObject
|
||||
|
||||
- (NSString *)description {
|
||||
|
||||
@@ -40,9 +40,9 @@
|
||||
#pragma mark MTLJSONSerializing
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
return [super.JSONKeyPathsByPropertyKey mtl_dictionaryByAddingEntriesFromDictionary:@{
|
||||
return @{
|
||||
@keypath(SQRLDownloadedUpdate.new, bundleURL): NSNull.null
|
||||
}];
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
//
|
||||
// SQRLInstaller+Private.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 08/01/2014.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLInstaller.h"
|
||||
|
||||
// The defaults key to store a `SQRLInstallerOwnedBundle` so that a moved bundle
|
||||
// can be restored.
|
||||
extern NSString * const SQRLInstallerOwnedBundleKey;
|
||||
|
||||
// The defaults key to store the number of installation attempts that have been
|
||||
// made.
|
||||
extern NSString * const SQRLShipItInstallationAttemptsKey;
|
||||
+20
-12
@@ -8,7 +8,10 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
// There was an error copying the target bundle to the backup location.
|
||||
// The domain for errors originating within SQRLInstaller.
|
||||
extern NSString * const SQRLInstallerErrorDomain;
|
||||
|
||||
// There was an error copying the target or update bundle to a backup location.
|
||||
extern const NSInteger SQRLInstallerErrorBackupFailed;
|
||||
|
||||
// There was an error replacing the target bundle with the update.
|
||||
@@ -31,25 +34,34 @@ extern const NSInteger SQRLInstallerErrorInvalidState;
|
||||
// There was an error moving a bundle across volumes.
|
||||
extern const NSInteger SQRLInstallerErrorMovingAcrossVolumes;
|
||||
|
||||
@class RACCommand;
|
||||
@class SQRLDirectoryManager;
|
||||
// There was an error changing the file permissions of the update.
|
||||
extern const NSInteger SQRLInstallerErrorChangingPermissions;
|
||||
|
||||
// Performs the installation of an update, using the `SQRLShipItState` on disk,
|
||||
// as located by `SQRLDirectoryManager`.
|
||||
@class RACCommand;
|
||||
|
||||
// Performs the installation of an update, saving its intermediate state to user
|
||||
// defaults.
|
||||
//
|
||||
// This class is meant to be used only after the app that will be updated has
|
||||
// terminated.
|
||||
@interface SQRLInstaller : NSObject
|
||||
|
||||
// When executed with a `SQRLShipItState`, attempts to install the update or
|
||||
// Initializes an installer using the given application identifier, which is
|
||||
// used to scope resumable state stored to user defaults.
|
||||
//
|
||||
// applicationIdentifier - The defaults domain in which to store resumable
|
||||
// state. Must not be nil.
|
||||
- (instancetype)initWithApplicationIdentifier:(NSString *)applicationIdentifier;
|
||||
|
||||
// When executed with a `SQRLShipItRequest`, attempts to install the update or
|
||||
// resume an in-progress installation.
|
||||
//
|
||||
// Each execution will complete or error on an unspecified scheduler when
|
||||
// installation has completed or failed.
|
||||
@property (nonatomic, strong, readonly) RACCommand *installUpdateCommand;
|
||||
|
||||
// When executed with a `SQRLShipItState`, aborts an installation, and attempts
|
||||
// to restore the old version of the application if necessary.
|
||||
// When executed with a `SQRLShipItRequest`, aborts an installation, and
|
||||
// attempts to restore the old version of the application if necessary.
|
||||
//
|
||||
// This must not be executed while `installUpdateCommand` is executing.
|
||||
//
|
||||
@@ -57,8 +69,4 @@ extern const NSInteger SQRLInstallerErrorMovingAcrossVolumes;
|
||||
// aborting/recovery has finished.
|
||||
@property (nonatomic, strong, readonly) RACCommand *abortInstallationCommand;
|
||||
|
||||
// Initializes an installer using the given directory manager to read and write the
|
||||
// state of the installation.
|
||||
- (id)initWithDirectoryManager:(SQRLDirectoryManager *)directoryManager;
|
||||
|
||||
@end
|
||||
|
||||
+396
-371
@@ -7,18 +7,27 @@
|
||||
//
|
||||
|
||||
#import "SQRLInstaller.h"
|
||||
|
||||
#import <libkern/OSAtomic.h>
|
||||
#import "EXTScope.h"
|
||||
#import <ReactiveCocoa/NSEnumerator+RACSequenceAdditions.h>
|
||||
#import <ReactiveCocoa/NSObject+RACPropertySubscribing.h>
|
||||
#import <ReactiveCocoa/RACCommand.h>
|
||||
#import <ReactiveCocoa/RACSequence.h>
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
#import <ReactiveCocoa/RACSubscriber.h>
|
||||
#import <sys/xattr.h>
|
||||
|
||||
#import "NSBundle+SQRLVersionExtensions.h"
|
||||
#import "NSError+SQRLVerbosityExtensions.h"
|
||||
#import "RACSignal+SQRLTransactionExtensions.h"
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLShipItState.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
#import "SQRLTerminationListener.h"
|
||||
#import <libkern/OSAtomic.h>
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <sys/xattr.h>
|
||||
#import "Squirrel-Constants.h"
|
||||
#import "SQRLInstallerOwnedBundle.h"
|
||||
|
||||
NSString * const SQRLInstallerErrorDomain = @"SQRLInstallerErrorDomain";
|
||||
|
||||
const NSInteger SQRLInstallerErrorBackupFailed = -1;
|
||||
const NSInteger SQRLInstallerErrorReplacingTarget = -2;
|
||||
@@ -27,85 +36,58 @@ const NSInteger SQRLInstallerErrorInvalidBundleVersion = -4;
|
||||
const NSInteger SQRLInstallerErrorMissingInstallationData = -5;
|
||||
const NSInteger SQRLInstallerErrorInvalidState = -6;
|
||||
const NSInteger SQRLInstallerErrorMovingAcrossVolumes = -7;
|
||||
const NSInteger SQRLInstallerErrorChangingPermissions = -8;
|
||||
|
||||
// Maps an installer state to a selector to invoke.
|
||||
typedef struct {
|
||||
// The state for which the associated method should be invoked.
|
||||
SQRLInstallerState installerState;
|
||||
|
||||
// A method accepting a `SQRLShipItState` argument and returning a cold
|
||||
// signal.
|
||||
//
|
||||
// If NULL, installation should complete.
|
||||
SEL selector;
|
||||
} SQRLInstallerDispatchTableEntry;
|
||||
NSString * const SQRLShipItInstallationAttemptsKey = @"SQRLShipItInstallationAttempts";
|
||||
NSString * const SQRLInstallerOwnedBundleKey = @"SQRLInstallerOwnedBundle";
|
||||
|
||||
@interface SQRLInstaller ()
|
||||
|
||||
// Finds the state file to read and write from.
|
||||
@property (nonatomic, strong, readonly) SQRLDirectoryManager *directoryManager;
|
||||
// The defaults domain to store all resumable state in.
|
||||
@property (nonatomic, copy, readonly) NSString *applicationIdentifier;
|
||||
|
||||
// Reads the given key from `state`, failing if it's not set.
|
||||
// The bundle currently owned by this installer.
|
||||
//
|
||||
// key - The property key to read from `state`. This must not be nil, and
|
||||
// should refer to a property of object type.
|
||||
// state - The state object to read. This must not be nil.
|
||||
// Stores the bundle moved aside by an install request so that the original
|
||||
// bundle can be restored to its original location if needed.
|
||||
@property (atomic, strong) SQRLInstallerOwnedBundle *ownedBundle;
|
||||
|
||||
// Reads the given key from `request`, failing if it's not set.
|
||||
//
|
||||
// key - The property key to read from `request`. This must not be nil, and
|
||||
// should refer to a property of object type.
|
||||
// request - The request object to read. This must not be nil.
|
||||
//
|
||||
// Returns a signal which synchronously sends the non-nil read value then
|
||||
// completes, or errors.
|
||||
- (RACSignal *)getRequiredKey:(NSString *)key fromState:(SQRLShipItState *)state;
|
||||
- (RACSignal *)getRequiredKey:(NSString *)key fromRequest:(SQRLShipItRequest *)request;
|
||||
|
||||
// Performs the remaining stages of installation, as specified by `state`.
|
||||
// Moves the updateBundleURL to an owned directory to prevent symlink attack,
|
||||
// takes user:group ownership of the bundle, then verifies that it meets the
|
||||
// designated requirement of the targetBundleURL.
|
||||
//
|
||||
// state - The installation state. This must not be nil.
|
||||
// request - The request whose update should be prepared and validated.
|
||||
//
|
||||
// Returns a signal which will complete or error on an unspecified thread.
|
||||
- (RACSignal *)resumeInstallationFromState:(SQRLShipItState *)state;
|
||||
// Returns a signal which sends the owned & validated bundle URL then completes,
|
||||
// or errors.
|
||||
- (RACSignal *)prepareAndValidateUpdateBundleURLForRequest:(SQRLShipItRequest *)request;
|
||||
|
||||
// Moves the specified bundle to a backup location.
|
||||
// Saves a `SQRLInstallerOwnedBundle` for the targetBundleURL to the
|
||||
// preferences, then moves the targetBundleURL to an owned directory.
|
||||
//
|
||||
// bundleURL - The URL to the bundle that should be backed up. This must not be
|
||||
// nil.
|
||||
// request - The request whose target should be removed in preparation of an
|
||||
// update being installed.
|
||||
//
|
||||
// Returns a signal which will send the `NSURL` to the proposed backup location
|
||||
// as soon as possible, then complete once the bundle has actually been moved.
|
||||
- (RACSignal *)backUpBundleAtURL:(NSURL *)bundleURL;
|
||||
// Returns a signal which completes, or errors.
|
||||
- (RACSignal *)acquireTargetBundleURLForRequest:(SQRLShipItRequest *)request;
|
||||
|
||||
// Deletes a bundle that was backed up using -backUpBundleAtURL:.
|
||||
// Deletes a bundle that was moved into place using -moveAndTakeOwnershipOfBundleAtURL:.
|
||||
//
|
||||
// backupURL - The URL to the backup bundle, as sent from -backUpBundleAtURL:.
|
||||
// bundleURL - The URL to the backup bundle, as sent from -moveAndTakeOwnershipOfBundleAtURL:.
|
||||
// This must not be nil.
|
||||
//
|
||||
// Returns a signal which will synchronously complete or error.
|
||||
- (RACSignal *)deleteBackupAtURL:(NSURL *)backupURL;
|
||||
|
||||
// Validates the code signature of a bundle, optionally restoring it upon
|
||||
// failure.
|
||||
//
|
||||
// bundleURL - The URL of the bundle whose code signature should be
|
||||
// verified. This must not be nil.
|
||||
// signature - The code signature that the bundle must match. This must
|
||||
// not be nil.
|
||||
// backupBundleURL - If not nil, the URL to a bundle that should replace
|
||||
// `bundleURL` if the code signature does not pass validation.
|
||||
//
|
||||
// Returns a signal which will synchronously complete if `bundleURL` passes
|
||||
// validation, or if the bundle was recovered from `backupBundleURL`. If
|
||||
// validation or recovery fails, an error will be sent.
|
||||
- (RACSignal *)verifyBundleAtURL:(NSURL *)bundleURL usingSignature:(SQRLCodeSignature *)signature recoveringUsingBackupAtURL:(NSURL *)backupBundleURL;
|
||||
|
||||
// Attempts to determine whether a bundle has already been moved on disk.
|
||||
//
|
||||
// sourceURL - The original URL to the bundle. This must not be nil.
|
||||
// targetURL - The proposed destination URL for the bundle. This must not be
|
||||
// nil.
|
||||
// signature - The code signature that any item must match in order to be
|
||||
// considered the correct bundle. This must not be nil.
|
||||
//
|
||||
// Returns a signal which will synchronously send YES if `targetURL` points to
|
||||
// a bundle matching the code signature, NO if it doesn't and `sourceURL` still
|
||||
// exists, or an error otherwise.
|
||||
- (RACSignal *)checkWhetherBundlePreviouslyAtURL:(NSURL *)sourceURL wasInstalledAtURL:(NSURL *)targetURL usingSignature:(SQRLCodeSignature *)signature;
|
||||
- (RACSignal *)deleteOwnedBundleAtURL:(NSURL *)bundleURL;
|
||||
|
||||
// Moves `sourceURL` to `targetURL`.
|
||||
//
|
||||
@@ -117,7 +99,7 @@ typedef struct {
|
||||
// sourceURL - The URL to move from. This must not be nil.
|
||||
//
|
||||
// Retruns a signal which will synchronously complete or error.
|
||||
- (RACSignal *)installItemAtURL:(NSURL *)targetURL fromURL:(NSURL *)sourceURL;
|
||||
- (RACSignal *)installItemToURL:(NSURL *)targetURL fromURL:(NSURL *)sourceURL;
|
||||
|
||||
// Recursively clears the quarantine extended attribute from the given
|
||||
// directory.
|
||||
@@ -131,19 +113,28 @@ typedef struct {
|
||||
// Returns a signal which will send completed or error on a background thread.
|
||||
- (RACSignal *)clearQuarantineForDirectory:(NSURL *)directory;
|
||||
|
||||
// Recursively changes the owner and group of the given directory tree to that
|
||||
// of the current process, then disables writing for anyone but the owner.
|
||||
//
|
||||
// directoryURL - The URL to the folder to take ownership of. This must not be
|
||||
// nil.
|
||||
//
|
||||
// Returns a signal which will synchronously complete or error.
|
||||
- (RACSignal *)takeOwnershipOfDirectory:(NSURL *)directoryURL;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SQRLInstaller
|
||||
|
||||
#pragma mark Lifecycle
|
||||
|
||||
- (id)initWithDirectoryManager:(SQRLDirectoryManager *)directoryManager {
|
||||
NSParameterAssert(directoryManager != nil);
|
||||
- (id)initWithApplicationIdentifier:(NSString *)applicationIdentifier {
|
||||
NSParameterAssert(applicationIdentifier != nil);
|
||||
|
||||
self = [super init];
|
||||
if (self == nil) return nil;
|
||||
|
||||
_directoryManager = directoryManager;
|
||||
_applicationIdentifier = [applicationIdentifier copy];
|
||||
|
||||
@weakify(self);
|
||||
|
||||
@@ -155,42 +146,63 @@ typedef struct {
|
||||
switchToLatest]
|
||||
setNameWithFormat:@"aborting"];
|
||||
|
||||
_installUpdateCommand = [[RACCommand alloc] initWithEnabled:[aborting not] signalBlock:^(SQRLShipItState *state) {
|
||||
_installUpdateCommand = [[RACCommand alloc] initWithEnabled:[aborting not] signalBlock:^(SQRLShipItRequest *request) {
|
||||
@strongify(self);
|
||||
NSParameterAssert(state != nil);
|
||||
NSParameterAssert(request != nil);
|
||||
|
||||
return [[self
|
||||
resumeInstallationFromState:state]
|
||||
sqrl_addTransactionWithName:NSLocalizedString(@"Updating", nil) description:NSLocalizedString(@"%@ is being updated, and interrupting the process could corrupt the application", nil), state.targetBundleURL.path];
|
||||
}];
|
||||
// Request can be changed between launches, the installer may have
|
||||
// already have an owned bundle, for a previous targetURL.
|
||||
//
|
||||
// If that's the case, we need to abort the previous owned bundle, and
|
||||
// then handle the new install request.
|
||||
|
||||
_abortInstallationCommand = [[RACCommand alloc] initWithEnabled:[self.installUpdateCommand.executing not] signalBlock:^(SQRLShipItState *state) {
|
||||
@strongify(self);
|
||||
NSParameterAssert(state != nil);
|
||||
|
||||
return [[[RACSignal
|
||||
zip:@[
|
||||
[self getRequiredKey:@keypath(state.targetBundleURL) fromState:state],
|
||||
[self getRequiredKey:@keypath(state.codeSignature) fromState:state]
|
||||
] reduce:^(NSURL *targetBundleURL, SQRLCodeSignature *codeSignature) {
|
||||
return [self verifyBundleAtURL:targetBundleURL usingSignature:codeSignature recoveringUsingBackupAtURL:state.backupBundleURL];
|
||||
return [[[[self
|
||||
abortInstall]
|
||||
doError:^(NSError *error) {
|
||||
NSLog(@"Couldn't abort install and restore owned bundle to previous location %@, error %@", self.ownedBundle.originalURL, error.sqrl_verboseDescription);
|
||||
}]
|
||||
flatten]
|
||||
sqrl_addTransactionWithName:NSLocalizedString(@"Aborting update", nil) description:NSLocalizedString(@"An update to %@ is being rolled back, and interrupting the process could corrupt the application", nil), state.targetBundleURL.path];
|
||||
catchTo:[RACSignal empty]]
|
||||
then:^{
|
||||
return [self installRequest:request];
|
||||
}];
|
||||
}];
|
||||
|
||||
|
||||
_abortInstallationCommand = [[RACCommand alloc] initWithEnabled:[self.installUpdateCommand.executing not] signalBlock:^(SQRLShipItRequest *request) {
|
||||
@strongify(self);
|
||||
|
||||
return [self abortInstall];
|
||||
}];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark Installer State
|
||||
#pragma mark Preferences
|
||||
|
||||
- (RACSignal *)getRequiredKey:(NSString *)key fromState:(SQRLShipItState *)state {
|
||||
- (SQRLInstallerOwnedBundle *)ownedBundle {
|
||||
id archiveData = CFBridgingRelease(CFPreferencesCopyValue((__bridge CFStringRef)SQRLInstallerOwnedBundleKey, (__bridge CFStringRef)self.applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost));
|
||||
if (![archiveData isKindOfClass:NSData.class]) return nil;
|
||||
|
||||
SQRLInstallerOwnedBundle *ownedBundle = [NSKeyedUnarchiver unarchiveObjectWithData:archiveData];
|
||||
if (![ownedBundle isKindOfClass:SQRLInstallerOwnedBundle.class]) return nil;
|
||||
|
||||
return ownedBundle;
|
||||
}
|
||||
|
||||
- (void)setOwnedBundle:(SQRLInstallerOwnedBundle *)ownedBundle {
|
||||
NSData *archiveData = (ownedBundle == nil ? nil : [NSKeyedArchiver archivedDataWithRootObject:ownedBundle]);
|
||||
CFPreferencesSetValue((__bridge CFStringRef)SQRLInstallerOwnedBundleKey, (__bridge CFPropertyListRef)archiveData, (__bridge CFStringRef)self.applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
CFPreferencesSynchronize((__bridge CFStringRef)self.applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
}
|
||||
|
||||
#pragma mark Properties
|
||||
|
||||
- (RACSignal *)getRequiredKey:(NSString *)key fromRequest:(SQRLShipItRequest *)request {
|
||||
NSParameterAssert(key != nil);
|
||||
NSParameterAssert(state != nil);
|
||||
NSParameterAssert(request != nil);
|
||||
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
id value = [state valueForKey:key];
|
||||
id value = [request valueForKey:key];
|
||||
if (value == nil) {
|
||||
NSString *errorDescription = [NSString stringWithFormat:NSLocalizedString(@"Missing %@", nil), key];
|
||||
return [RACSignal error:[self missingDataErrorWithDescription:errorDescription]];
|
||||
@@ -198,271 +210,184 @@ typedef struct {
|
||||
return [RACSignal return:value];
|
||||
}
|
||||
}]
|
||||
setNameWithFormat:@"%@ -getRequiredKey: %@ fromState: %@", self, key, state];
|
||||
setNameWithFormat:@"%@ -getRequiredKey: %@ fromRequest: %@", self, key, request];
|
||||
}
|
||||
|
||||
- (RACSignal *)resumeInstallationFromState:(SQRLShipItState *)state {
|
||||
NSParameterAssert(state != nil);
|
||||
#pragma mark Installer States
|
||||
|
||||
const SQRLInstallerDispatchTableEntry dispatchTablePrototype[] = {
|
||||
{ .installerState = SQRLInstallerStateNothingToDo, .selector = NULL },
|
||||
{ .installerState = SQRLInstallerStateClearingQuarantine, .selector = @selector(clearQuarantineWithState:) },
|
||||
{ .installerState = SQRLInstallerStateBackingUp, .selector = @selector(backUpWithState:) },
|
||||
{ .installerState = SQRLInstallerStateInstalling, .selector = @selector(installWithState:) },
|
||||
{ .installerState = SQRLInstallerStateVerifyingInPlace, .selector = @selector(verifyInPlaceWithState:) },
|
||||
{ .installerState = SQRLInstallerStateRelaunching, .selector = @selector(relaunchWithState:) },
|
||||
};
|
||||
- (RACSignal *)prepareAndValidateUpdateBundleURLForRequest:(SQRLShipItRequest *)request {
|
||||
NSParameterAssert(request != nil);
|
||||
|
||||
const size_t tableCount = sizeof(dispatchTablePrototype) / sizeof(*dispatchTablePrototype);
|
||||
NSValue *boxedDispatchTable = [NSValue valueWithBytes:dispatchTablePrototype objCType:@encode(__typeof__(dispatchTablePrototype))];
|
||||
return [[[[[[[self
|
||||
ownedTemporaryDirectoryURL]
|
||||
flattenMap:^(NSURL *directoryURL) {
|
||||
return [self copyBundleAtURL:request.updateBundleURL toDirectory:directoryURL];
|
||||
}]
|
||||
flattenMap:^(NSURL *bundleURL) {
|
||||
return [[[self
|
||||
clearQuarantineForDirectory:bundleURL]
|
||||
ignoreValues]
|
||||
concat:[RACSignal return:bundleURL]];
|
||||
}]
|
||||
zipWith:[self codeSignatureForBundleAtURL:request.targetBundleURL]]
|
||||
reduceEach:^(NSURL *updateBundleURL, SQRLCodeSignature *codeSignature) {
|
||||
return [[[self
|
||||
verifyBundleAtURL:updateBundleURL usingSignature:codeSignature]
|
||||
ignoreValues]
|
||||
concat:[RACSignal return:updateBundleURL]];
|
||||
}]
|
||||
flatten]
|
||||
setNameWithFormat:@"%@ -prepareAndValidateUpdateBundleURLForRequest: %@", self, request];
|
||||
}
|
||||
|
||||
RACSignal *step = [RACSignal defer:^{
|
||||
SQRLInstallerDispatchTableEntry dispatchTable[tableCount];
|
||||
[boxedDispatchTable getValue:&dispatchTable];
|
||||
- (RACSignal *)acquireTargetBundleURLForRequest:(SQRLShipItRequest *)request {
|
||||
NSParameterAssert(request != nil);
|
||||
|
||||
SQRLInstallerState installerState = state.installerState;
|
||||
return [[[[RACSignal
|
||||
zip:@[
|
||||
[self ownedTemporaryDirectoryURL],
|
||||
[self codeSignatureForBundleAtURL:request.targetBundleURL],
|
||||
] reduce:^(NSURL *directoryURL, SQRLCodeSignature *codeSignature) {
|
||||
NSURL *targetBundleURL = request.targetBundleURL;
|
||||
NSURL *newBundleURL = [directoryURL URLByAppendingPathComponent:targetBundleURL.lastPathComponent];
|
||||
|
||||
size_t tableIndex;
|
||||
for (tableIndex = 0; tableIndex < tableCount; tableIndex++) {
|
||||
if (dispatchTable[tableIndex].installerState == installerState) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return [[SQRLInstallerOwnedBundle alloc] initWithOriginalURL:request.targetBundleURL temporaryURL:newBundleURL codeSignature:codeSignature];
|
||||
}]
|
||||
doNext:^(SQRLInstallerOwnedBundle *ownedBundle) {
|
||||
self.ownedBundle = ownedBundle;
|
||||
}]
|
||||
flattenMap:^(SQRLInstallerOwnedBundle *ownedBundle) {
|
||||
return [self installItemToURL:ownedBundle.temporaryURL fromURL:ownedBundle.originalURL];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -acquireTargetBundleURLForRequest: %@", self, request];
|
||||
}
|
||||
|
||||
if (tableIndex >= tableCount) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"Invalid installer state %i", nil), (int)installerState],
|
||||
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Try installing the update again.", nil)
|
||||
};
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLErrorDomain code:SQRLInstallerErrorInvalidState userInfo:userInfo]];
|
||||
}
|
||||
|
||||
SEL selector = dispatchTable[tableIndex].selector;
|
||||
if (selector == NULL) {
|
||||
// Nothing to do.
|
||||
return [RACSignal empty];
|
||||
}
|
||||
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:selector]];
|
||||
invocation.target = self;
|
||||
invocation.selector = selector;
|
||||
|
||||
SQRLShipItState *stateArg = state;
|
||||
[invocation setArgument:&stateArg atIndex:2];
|
||||
[invocation invoke];
|
||||
|
||||
__unsafe_unretained RACSignal *step = nil;
|
||||
[invocation getReturnValue:&step];
|
||||
|
||||
SQRLInstallerState nextState;
|
||||
if (tableIndex + 1 >= tableCount) {
|
||||
nextState = SQRLInstallerStateNothingToDo;
|
||||
} else {
|
||||
nextState = dispatchTable[tableIndex + 1].installerState;
|
||||
}
|
||||
|
||||
return [[step
|
||||
doCompleted:^{
|
||||
NSLog(@"Completed state %i", (int)installerState);
|
||||
}]
|
||||
then:^{
|
||||
return [RACSignal return:@(nextState)];
|
||||
}];
|
||||
}];
|
||||
- (RACSignal *)renameIfNeeded:(SQRLShipItRequest *)request updateBundleURL:(NSURL *)updateBundleURL {
|
||||
if (!request.useUpdateBundleName) return [RACSignal return:request];
|
||||
|
||||
return [[self
|
||||
stepRepeatedly:step withState:state]
|
||||
setNameWithFormat:@"%@ -resumeInstallationFromState: %@", self, state];
|
||||
}
|
||||
renamedTargetIfNeededWithTargetURL:request.targetBundleURL sourceURL:updateBundleURL]
|
||||
flattenMap:^(NSURL *newTargetURL) {
|
||||
if ([newTargetURL isEqual:request.targetBundleURL]) return [RACSignal return:request];
|
||||
|
||||
- (RACSignal *)stepRepeatedly:(RACSignal *)step withState:(SQRLShipItState *)state {
|
||||
NSParameterAssert(step != nil);
|
||||
NSParameterAssert(state != nil);
|
||||
|
||||
return [step flattenMap:^(NSNumber *nextState) {
|
||||
state.installerState = nextState.integerValue;
|
||||
state.installationStateAttempt = 1;
|
||||
return [[state
|
||||
writeUsingURL:self.directoryManager.shipItStateURL]
|
||||
// Automatically begin the next step.
|
||||
concat:[self stepRepeatedly:step withState:state]];
|
||||
}];
|
||||
}
|
||||
|
||||
- (RACSignal *)clearQuarantineWithState:(SQRLShipItState *)state {
|
||||
NSParameterAssert(state != nil);
|
||||
|
||||
return [[[self
|
||||
getRequiredKey:@keypath(state.updateBundleURL) fromState:state]
|
||||
flattenMap:^(NSURL *bundleURL) {
|
||||
return [self clearQuarantineForDirectory:bundleURL];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -clearQuarantineWithState: %@", self, state];
|
||||
}
|
||||
|
||||
- (RACSignal *)backUpWithState:(SQRLShipItState *)state {
|
||||
NSParameterAssert(state != nil);
|
||||
|
||||
return [[[[RACSignal
|
||||
zip:@[
|
||||
[self getRequiredKey:@keypath(state.targetBundleURL) fromState:state],
|
||||
[self getRequiredKey:@keypath(state.codeSignature) fromState:state],
|
||||
] reduce:^(NSURL *bundleURL, SQRLCodeSignature *codeSignature) {
|
||||
RACSignal *skipBackup = [RACSignal return:@NO];
|
||||
if (state.backupBundleURL != nil) {
|
||||
skipBackup = [self checkWhetherBundlePreviouslyAtURL:bundleURL wasInstalledAtURL:state.backupBundleURL usingSignature:codeSignature];
|
||||
}
|
||||
|
||||
return [skipBackup flattenMap:^(NSNumber *skip) {
|
||||
if (skip.boolValue) {
|
||||
return [RACSignal empty];
|
||||
} else {
|
||||
return [self backUpBundleAtURL:bundleURL];
|
||||
}
|
||||
}];
|
||||
}]
|
||||
flatten]
|
||||
flattenMap:^(NSURL *backupBundleURL) {
|
||||
// Save the chosen backup URL as soon as we have it, so we
|
||||
// can resume even if the state change hasn't taken effect.
|
||||
//
|
||||
// N.B. It's important that this method remain
|
||||
// synchronous, so it finishes before returning
|
||||
// control to -backUpBundleAtURL:. Really, the flow
|
||||
// here should be refactored so it doesn't matter.
|
||||
state.backupBundleURL = backupBundleURL;
|
||||
return [state writeUsingURL:self.directoryManager.shipItStateURL];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -backUpWithState: %@", self, state];
|
||||
}
|
||||
|
||||
- (RACSignal *)installWithState:(SQRLShipItState *)state {
|
||||
NSParameterAssert(state != nil);
|
||||
|
||||
return [[[RACSignal
|
||||
zip:@[
|
||||
[self getRequiredKey:@keypath(state.targetBundleURL) fromState:state],
|
||||
[self getRequiredKey:@keypath(state.updateBundleURL) fromState:state],
|
||||
[self getRequiredKey:@keypath(state.backupBundleURL) fromState:state],
|
||||
[self getRequiredKey:@keypath(state.codeSignature) fromState:state]
|
||||
] reduce:^(NSURL *targetBundleURL, NSURL *updateBundleURL, NSURL *backupBundleURL, SQRLCodeSignature *codeSignature) {
|
||||
return [[[[self
|
||||
checkWhetherBundlePreviouslyAtURL:updateBundleURL wasInstalledAtURL:targetBundleURL usingSignature:codeSignature]
|
||||
flattenMap:^(NSNumber *skip) {
|
||||
if (skip.boolValue) {
|
||||
return [RACSignal empty];
|
||||
} else {
|
||||
return [self installItemAtURL:targetBundleURL fromURL:updateBundleURL];
|
||||
}
|
||||
}]
|
||||
catch:^(NSError *error) {
|
||||
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"Failed to replace bundle %@ with update %@", nil), targetBundleURL, updateBundleURL];
|
||||
return [RACSignal error:[self errorByAddingDescription:description code:SQRLInstallerErrorReplacingTarget toError:error]];
|
||||
}]
|
||||
catch:^(NSError *error) {
|
||||
// Verify that the target bundle didn't get corrupted during
|
||||
// failure. Try recovering it if it did.
|
||||
return [[self
|
||||
verifyBundleAtURL:targetBundleURL usingSignature:codeSignature recoveringUsingBackupAtURL:backupBundleURL]
|
||||
then:^{
|
||||
// Recovery succeeded, but we still want to pass
|
||||
// through the original error.
|
||||
return [RACSignal error:error];
|
||||
}];
|
||||
}];
|
||||
}]
|
||||
flatten]
|
||||
setNameWithFormat:@"%@ -installWithState: %@", self, state];
|
||||
}
|
||||
|
||||
- (RACSignal *)verifyInPlaceWithState:(SQRLShipItState *)state {
|
||||
NSParameterAssert(state != nil);
|
||||
|
||||
return [[[RACSignal
|
||||
zip:@[
|
||||
[self getRequiredKey:@keypath(state.targetBundleURL) fromState:state],
|
||||
[self getRequiredKey:@keypath(state.backupBundleURL) fromState:state],
|
||||
[self getRequiredKey:@keypath(state.codeSignature) fromState:state]
|
||||
] reduce:^(NSURL *targetBundleURL, NSURL *backupBundleURL, SQRLCodeSignature *codeSignature) {
|
||||
SQRLShipItRequest *updatedRequest = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:request.updateBundleURL targetBundleURL:newTargetURL bundleIdentifier:request.bundleIdentifier launchAfterInstallation:request.launchAfterInstallation useUpdateBundleName:request.useUpdateBundleName];
|
||||
return [[self
|
||||
verifyBundleAtURL:targetBundleURL usingSignature:codeSignature recoveringUsingBackupAtURL:backupBundleURL]
|
||||
then:^{
|
||||
return [[self
|
||||
deleteBackupAtURL:backupBundleURL]
|
||||
catchTo:[RACSignal empty]];
|
||||
installItemToURL:newTargetURL fromURL:request.targetBundleURL]
|
||||
concat:[RACSignal return:updatedRequest]];
|
||||
}];
|
||||
}
|
||||
|
||||
- (RACSignal *)installRequest:(SQRLShipItRequest *)request {
|
||||
NSParameterAssert(request != nil);
|
||||
|
||||
return [[[[self
|
||||
prepareAndValidateUpdateBundleURLForRequest:request]
|
||||
flattenMap:^(NSURL *updateBundleURL) {
|
||||
return [[[[self
|
||||
renameIfNeeded:request updateBundleURL:updateBundleURL]
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return [[self acquireTargetBundleURLForRequest:request] concat:[RACSignal return:request]];
|
||||
}]
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return [[[[[[self
|
||||
installItemToURL:request.targetBundleURL fromURL:updateBundleURL]
|
||||
concat:[RACSignal return:request.updateBundleURL]]
|
||||
concat:[RACSignal return:updateBundleURL]]
|
||||
concat:[RACSignal defer:^{
|
||||
return [RACSignal return:self.ownedBundle.temporaryURL];
|
||||
}]]
|
||||
flattenMap:^(NSURL *location) {
|
||||
return [[[self
|
||||
deleteOwnedBundleAtURL:location]
|
||||
doError:^(NSError *error) {
|
||||
NSLog(@"Couldn't remove owned bundle at location %@, error %@", location, error.sqrl_verboseDescription);
|
||||
}]
|
||||
catchTo:[RACSignal empty]];
|
||||
}]
|
||||
concat:[RACSignal return:request]];
|
||||
}]
|
||||
doCompleted:^{
|
||||
self.ownedBundle = nil;
|
||||
}];
|
||||
}]
|
||||
flatten]
|
||||
setNameWithFormat:@"%@ -verifyInPlaceWithState: %@", self, state];
|
||||
sqrl_addTransactionWithName:NSLocalizedString(@"Updating", nil) description:NSLocalizedString(@"%@ is being updated, and interrupting the process could corrupt the application", nil), request.targetBundleURL.path]
|
||||
setNameWithFormat:@"%@ -installRequest: %@", self, request];
|
||||
}
|
||||
|
||||
- (RACSignal *)relaunchWithState:(SQRLShipItState *)state {
|
||||
return [[[[RACSignal
|
||||
- (RACSignal *)abortInstall {
|
||||
// The request may have been tampered with to select a new targetURL to
|
||||
// which the moved bundles should be restored.
|
||||
//
|
||||
// Discard the request parameters and restore the owned bundle to its
|
||||
// original location.
|
||||
|
||||
SQRLInstallerOwnedBundle *ownedBundle = self.ownedBundle;
|
||||
if (ownedBundle == nil) return [RACSignal empty];
|
||||
|
||||
return [[[[self
|
||||
installItemToURL:ownedBundle.originalURL fromURL:ownedBundle.temporaryURL]
|
||||
doCompleted:^{
|
||||
self.ownedBundle = nil;
|
||||
}]
|
||||
sqrl_addTransactionWithName:NSLocalizedString(@"Aborting update", nil) description:NSLocalizedString(@"An update to %@ is being rolled back, and interrupting the process could corrupt the application", nil), ownedBundle.originalURL.path]
|
||||
setNameWithFormat:@"%@ -abortInstall", self];
|
||||
}
|
||||
|
||||
#pragma mark Bundle Ownership
|
||||
|
||||
- (RACSignal *)ownedTemporaryDirectoryURL {
|
||||
return [[[RACSignal
|
||||
defer:^{
|
||||
if (state.relaunchAfterInstallation) {
|
||||
return [self getRequiredKey:@keypath(state.targetBundleURL) fromState:state];
|
||||
} else {
|
||||
return [RACSignal empty];
|
||||
}
|
||||
}]
|
||||
deliverOn:RACScheduler.mainThreadScheduler]
|
||||
flattenMap:^(NSURL *bundleURL) {
|
||||
NSError *error = nil;
|
||||
if ([NSWorkspace.sharedWorkspace launchApplicationAtURL:bundleURL options:NSWorkspaceLaunchDefault configuration:nil error:&error]) {
|
||||
return [RACSignal empty];
|
||||
} else {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
}]
|
||||
setNameWithFormat:@"%@ -relaunch", self];
|
||||
}
|
||||
NSString *tmpPath = [NSTemporaryDirectory() stringByResolvingSymlinksInPath];
|
||||
NSString *template = [NSString stringWithFormat:@"%@.XXXXXXXX", self.applicationIdentifier];
|
||||
|
||||
#pragma mark Backing Up
|
||||
char *fullTemplate = strdup([tmpPath stringByAppendingPathComponent:template].UTF8String);
|
||||
@onExit {
|
||||
free(fullTemplate);
|
||||
};
|
||||
|
||||
- (RACSignal *)backUpBundleAtURL:(NSURL *)targetBundleURL {
|
||||
NSParameterAssert(targetBundleURL != nil);
|
||||
|
||||
return [[[[[[self.directoryManager
|
||||
applicationSupportURL]
|
||||
flattenMap:^(NSURL *applicationSupportURL) {
|
||||
NSError *error = nil;
|
||||
NSURL *temporaryDirectoryURL = [NSFileManager.defaultManager URLForDirectory:NSItemReplacementDirectory inDomain:NSUserDomainMask appropriateForURL:applicationSupportURL create:YES error:&error];
|
||||
if (temporaryDirectoryURL == nil) {
|
||||
return [RACSignal error:error];
|
||||
if (mkdtemp(fullTemplate) == NULL) {
|
||||
return [RACSignal error:[NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:nil]];
|
||||
}
|
||||
|
||||
return [RACSignal return:temporaryDirectoryURL];
|
||||
NSURL *URL = [NSURL fileURLWithPath:[NSFileManager.defaultManager stringWithFileSystemRepresentation:fullTemplate length:strlen(fullTemplate)] isDirectory:YES];
|
||||
return [RACSignal return:URL];
|
||||
}]
|
||||
catch:^(NSError *error) {
|
||||
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"Could not create backup folder", nil)];
|
||||
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"Could not create temporary folder", nil)];
|
||||
return [RACSignal error:[self errorByAddingDescription:description code:SQRLInstallerErrorBackupFailed toError:error]];
|
||||
}]
|
||||
map:^(NSURL *temporaryDirectoryURL) {
|
||||
return [temporaryDirectoryURL URLByAppendingPathComponent:targetBundleURL.lastPathComponent];
|
||||
}]
|
||||
flattenMap:^(NSURL *backupBundleURL) {
|
||||
return [[[[self
|
||||
installItemAtURL:backupBundleURL fromURL:targetBundleURL]
|
||||
catch:^(NSError *error) {
|
||||
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"Failed to move bundle %@ to backup location %@", nil), targetBundleURL, backupBundleURL];
|
||||
return [RACSignal error:[self errorByAddingDescription:description code:SQRLInstallerErrorBackupFailed toError:error]];
|
||||
}]
|
||||
ignoreValues]
|
||||
// Return the backup URL before doing any work, to increase
|
||||
// fault tolerance.
|
||||
startWith:backupBundleURL];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -backUpBundleAtURL: %@", self, targetBundleURL];
|
||||
setNameWithFormat:@"%@ -ownedDirectoryURL", self];
|
||||
}
|
||||
|
||||
- (RACSignal *)deleteBackupAtURL:(NSURL *)backupURL {
|
||||
NSParameterAssert(backupURL != nil);
|
||||
- (RACSignal *)copyBundleAtURL:(NSURL *)bundleURL toDirectory:(NSURL *)directoryURL {
|
||||
NSParameterAssert(bundleURL != nil);
|
||||
NSParameterAssert(directoryURL != nil);
|
||||
|
||||
NSURL *newBundleURL = [directoryURL URLByAppendingPathComponent:bundleURL.lastPathComponent];
|
||||
|
||||
return [[[RACSignal
|
||||
defer:^{
|
||||
NSError *error = nil;
|
||||
if ([NSFileManager.defaultManager removeItemAtURL:backupURL error:&error]) {
|
||||
NSError *error;
|
||||
BOOL copy = [NSFileManager.defaultManager copyItemAtURL:bundleURL toURL:newBundleURL error:&error];
|
||||
if (!copy) return [RACSignal error:error];
|
||||
|
||||
return [RACSignal return:newBundleURL];
|
||||
}]
|
||||
catch:^(NSError *error) {
|
||||
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"Failed to copy bundle %@ to directory %@", nil), bundleURL, newBundleURL];
|
||||
return [RACSignal error:[self errorByAddingDescription:description code:SQRLInstallerErrorBackupFailed toError:error]];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -copyBundleAtURL: %@ toDirectory: %@", self, bundleURL, directoryURL];
|
||||
}
|
||||
|
||||
- (RACSignal *)deleteOwnedBundleAtURL:(NSURL *)bundleURL {
|
||||
NSParameterAssert(bundleURL != nil);
|
||||
|
||||
return [[[RACSignal
|
||||
defer:^{
|
||||
NSError *error;
|
||||
if ([NSFileManager.defaultManager removeItemAtURL:bundleURL error:&error]) {
|
||||
return [RACSignal empty];
|
||||
} else {
|
||||
return [RACSignal error:error];
|
||||
@@ -470,7 +395,7 @@ typedef struct {
|
||||
}]
|
||||
then:^{
|
||||
// Also remove the temporary directory that the backup lived in.
|
||||
NSURL *temporaryDirectoryURL = backupURL.URLByDeletingLastPathComponent;
|
||||
NSURL *temporaryDirectoryURL = bundleURL.URLByDeletingLastPathComponent;
|
||||
|
||||
// However, use rmdir() to skip it in case there are other files
|
||||
// contained within (for whatever reason).
|
||||
@@ -480,58 +405,67 @@ typedef struct {
|
||||
return [RACSignal error:[NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:nil]];
|
||||
}
|
||||
}]
|
||||
setNameWithFormat:@"%@ -deleteBackupAtURL: %@", self, backupURL];
|
||||
setNameWithFormat:@"%@ -deleteOwnedBundleAtURL: %@", self, bundleURL];
|
||||
}
|
||||
|
||||
- (RACSignal *)verifyBundleAtURL:(NSURL *)bundleURL usingSignature:(SQRLCodeSignature *)signature recoveringUsingBackupAtURL:(NSURL *)backupBundleURL {
|
||||
#pragma mark Verification
|
||||
|
||||
- (RACSignal *)codeSignatureForBundleAtURL:(NSURL *)URL {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
NSError *error;
|
||||
SQRLCodeSignature *codeSignature = [SQRLCodeSignature signatureWithBundle:URL error:&error];
|
||||
if (codeSignature == nil) return [RACSignal error:error];
|
||||
return [RACSignal return:codeSignature];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -codeSignatureForBundleAtURL: %@", self, URL];
|
||||
}
|
||||
|
||||
- (RACSignal *)verifyBundleAtURL:(NSURL *)bundleURL usingSignature:(SQRLCodeSignature *)signature {
|
||||
NSParameterAssert(bundleURL != nil);
|
||||
NSParameterAssert(signature != nil);
|
||||
|
||||
return [[[signature
|
||||
verifyBundleAtURL:bundleURL]
|
||||
catch:^(NSError *error) {
|
||||
if (backupBundleURL == nil) return [RACSignal error:error];
|
||||
|
||||
return [[[[self
|
||||
installItemAtURL:bundleURL fromURL:backupBundleURL]
|
||||
initially:^{
|
||||
[NSFileManager.defaultManager removeItemAtURL:bundleURL error:NULL];
|
||||
}]
|
||||
doCompleted:^{
|
||||
NSLog(@"Restored backup bundle to %@", bundleURL);
|
||||
}]
|
||||
doError:^(NSError *recoveryError) {
|
||||
NSLog(@"Could not restore backup bundle %@ to %@: %@", backupBundleURL, bundleURL, recoveryError.sqrl_verboseDescription);
|
||||
}];
|
||||
return [[[self
|
||||
takeOwnershipOfDirectory:bundleURL]
|
||||
then:^{
|
||||
return [signature verifyBundleAtURL:bundleURL];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -verifyBundleAtURL: %@ usingSignature: %@ recoveringUsingBackupAtURL: %@", self, bundleURL, signature, backupBundleURL];
|
||||
setNameWithFormat:@"%@ -verifyBundleAtURL: %@ usingSignature: %@", self, bundleURL, signature];
|
||||
}
|
||||
|
||||
#pragma mark Installation
|
||||
|
||||
- (RACSignal *)checkWhetherBundlePreviouslyAtURL:(NSURL *)sourceURL wasInstalledAtURL:(NSURL *)targetURL usingSignature:(SQRLCodeSignature *)signature {
|
||||
NSParameterAssert(targetURL != nil);
|
||||
NSParameterAssert(sourceURL != nil);
|
||||
NSParameterAssert(signature != nil);
|
||||
/// Check if the target should be renamed and provide the renamed URL.
|
||||
///
|
||||
/// targetURL - The URL for the target. Cannot be nil.
|
||||
/// sourceURL - The URL for the source. Cannot be nil.
|
||||
///
|
||||
/// Returns a signal which will send the URL for the renamed target. If a rename
|
||||
/// isn't needed then it will send `targetURL`.
|
||||
- (RACSignal *)renamedTargetIfNeededWithTargetURL:(NSURL *)targetURL sourceURL:(NSURL *)sourceURL {
|
||||
return [RACSignal defer:^{
|
||||
NSBundle *sourceBundle = [NSBundle bundleWithURL:sourceURL];
|
||||
NSString *targetExecutableName = targetURL.lastPathComponent.stringByDeletingPathExtension;
|
||||
NSString *sourceExecutableName = sourceBundle.sqrl_executableName;
|
||||
|
||||
return [[[[self
|
||||
verifyBundleAtURL:targetURL usingSignature:signature recoveringUsingBackupAtURL:nil]
|
||||
then:^{
|
||||
return [RACSignal return:@YES];
|
||||
}]
|
||||
catch:^(NSError *error) {
|
||||
BOOL directory;
|
||||
if ([NSFileManager.defaultManager fileExistsAtPath:sourceURL.path isDirectory:&directory]) {
|
||||
// If the source still exists, this isn't an error.
|
||||
return [RACSignal return:@NO];
|
||||
} else {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
}]
|
||||
setNameWithFormat:@"%@ -checkWhetherBundlePreviouslyAtURL: %@ wasInstalledAtURL: %@", self, sourceURL, targetURL];
|
||||
// If they're already the same then we're good.
|
||||
if ([targetExecutableName isEqual:sourceExecutableName]) {
|
||||
return [RACSignal return:targetURL];
|
||||
}
|
||||
|
||||
NSString *newAppName = [sourceExecutableName stringByAppendingPathExtension:@"app"];
|
||||
NSURL *newTargetURL = [targetURL.URLByDeletingLastPathComponent URLByAppendingPathComponent:newAppName];
|
||||
|
||||
// If there's already something there then don't rename to it.
|
||||
if ([NSFileManager.defaultManager fileExistsAtPath:newTargetURL.path]) {
|
||||
return [RACSignal return:targetURL];
|
||||
}
|
||||
|
||||
return [RACSignal return:newTargetURL];
|
||||
}];
|
||||
}
|
||||
|
||||
- (RACSignal *)installItemAtURL:(NSURL *)targetURL fromURL:(NSURL *)sourceURL {
|
||||
- (RACSignal *)installItemToURL:(NSURL *)targetURL fromURL:(NSURL *)sourceURL {
|
||||
NSParameterAssert(targetURL != nil);
|
||||
NSParameterAssert(sourceURL != nil);
|
||||
|
||||
@@ -543,7 +477,7 @@ typedef struct {
|
||||
} else {
|
||||
int code = errno;
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
|
||||
|
||||
|
||||
const char *desc = strerror(code);
|
||||
if (desc != NULL) userInfo[NSLocalizedDescriptionKey] = @(desc);
|
||||
|
||||
@@ -595,7 +529,7 @@ typedef struct {
|
||||
// file to begin with.
|
||||
if (code != ENOATTR) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
|
||||
|
||||
|
||||
const char *desc = strerror(code);
|
||||
if (desc != NULL) userInfo[NSLocalizedDescriptionKey] = @(desc);
|
||||
|
||||
@@ -608,6 +542,97 @@ typedef struct {
|
||||
setNameWithFormat:@"%@ -clearQuarantineForDirectory: %@", self, directory];
|
||||
}
|
||||
|
||||
#pragma mark File Security
|
||||
|
||||
- (RACSignal *)readFileSecurityOfURL:(NSURL *)location {
|
||||
NSParameterAssert(location != nil);
|
||||
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
NSError *error;
|
||||
NSFileSecurity *fileSecurity;
|
||||
if (![location getResourceValue:&fileSecurity forKey:NSURLFileSecurityKey error:&error]) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
return [RACSignal return:fileSecurity];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -readFileSecurity: %@", self, location];
|
||||
}
|
||||
|
||||
- (RACSignal *)writeFileSecurity:(NSFileSecurity *)fileSecurity toURL:(NSURL *)location {
|
||||
NSParameterAssert(location != nil);
|
||||
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
NSError *error;
|
||||
if (![location setResourceValue:fileSecurity forKey:NSURLFileSecurityKey error:&error]) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -writeFileSecurity: %@", self, location];
|
||||
}
|
||||
|
||||
- (RACSignal *)takeOwnershipOfDirectory:(NSURL *)directoryURL {
|
||||
NSParameterAssert(directoryURL != nil);
|
||||
|
||||
return [[[RACSignal
|
||||
createSignal:^(id<RACSubscriber> subscriber) {
|
||||
NSDirectoryEnumerator *enumerator = [NSFileManager.defaultManager enumeratorAtURL:directoryURL includingPropertiesForKeys:@[ NSURLFileSecurityKey ] options:0 errorHandler:^ BOOL (NSURL *url, NSError *error) {
|
||||
[subscriber sendError:error];
|
||||
return NO;
|
||||
}];
|
||||
|
||||
return [[enumerator.rac_sequence.signal
|
||||
startWith:directoryURL]
|
||||
subscribe:subscriber];
|
||||
}]
|
||||
flattenMap:^(NSURL *itemURL) {
|
||||
return [[[self
|
||||
readFileSecurityOfURL:itemURL]
|
||||
flattenMap:^(NSFileSecurity *fileSecurity) {
|
||||
if (![self takeOwnershipOfFileSecurity:fileSecurity]) {
|
||||
NSDictionary *errorInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Permissions Error", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Couldn’t update permissions of %@", nil), itemURL.path],
|
||||
NSURLErrorKey: itemURL
|
||||
};
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLInstallerErrorDomain code:SQRLInstallerErrorChangingPermissions userInfo:errorInfo]];
|
||||
}
|
||||
|
||||
return [RACSignal return:fileSecurity];
|
||||
}]
|
||||
flattenMap:^(NSFileSecurity *fileSecurity) {
|
||||
return [self writeFileSecurity:fileSecurity toURL:itemURL];
|
||||
}];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -takeOwnershipOfDirectory: %@", self, directoryURL];
|
||||
}
|
||||
|
||||
- (BOOL)takeOwnershipOfFileSecurity:(NSFileSecurity *)fileSecurity {
|
||||
CFFileSecurityRef actualFileSecurity = (__bridge CFFileSecurityRef)fileSecurity;
|
||||
|
||||
// If ShipIt is running as root, this will change the owner to
|
||||
// root:wheel.
|
||||
if (!CFFileSecuritySetOwner(actualFileSecurity, getuid())) return NO;
|
||||
if (!CFFileSecuritySetGroup(actualFileSecurity, getgid())) return NO;
|
||||
|
||||
mode_t fileMode = 0;
|
||||
if (!CFFileSecurityGetMode(actualFileSecurity, &fileMode)) return NO;
|
||||
|
||||
// Remove write permission from group and other, leave executable
|
||||
// bit as it was for both.
|
||||
//
|
||||
// Permissions will be r-(x?)r-(x?) afterwards, with owner
|
||||
// permissions left as is.
|
||||
fileMode = (fileMode & ~(S_IWGRP | S_IWOTH));
|
||||
|
||||
return CFFileSecuritySetMode(actualFileSecurity, fileMode);
|
||||
}
|
||||
|
||||
#pragma mark Error Handling
|
||||
|
||||
- (NSError *)missingDataErrorWithDescription:(NSString *)description {
|
||||
@@ -618,7 +643,7 @@ typedef struct {
|
||||
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Try installing the update again.", nil)
|
||||
};
|
||||
|
||||
return [NSError errorWithDomain:SQRLErrorDomain code:SQRLInstallerErrorMissingInstallationData userInfo:userInfo];
|
||||
return [NSError errorWithDomain:SQRLInstallerErrorDomain code:SQRLInstallerErrorMissingInstallationData userInfo:userInfo];
|
||||
}
|
||||
|
||||
- (NSError *)errorByAddingDescription:(NSString *)description code:(NSInteger)code toError:(NSError *)error {
|
||||
@@ -627,7 +652,7 @@ typedef struct {
|
||||
if (description != nil) userInfo[NSLocalizedDescriptionKey] = description;
|
||||
if (error != nil) userInfo[NSUnderlyingErrorKey] = error;
|
||||
|
||||
return [NSError errorWithDomain:SQRLErrorDomain code:code userInfo:userInfo];
|
||||
return [NSError errorWithDomain:SQRLInstallerErrorDomain code:code userInfo:userInfo];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//
|
||||
// SQRLInstallerOwnedBundle.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 08/01/2014.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
|
||||
@class SQRLCodeSignature;
|
||||
|
||||
// Tracks original and temporary locations of a bundle. Should be created and
|
||||
// serialised before moving a bundle aside.
|
||||
//
|
||||
// Can be used to ensure new targetURL requests meet the original bundle at that
|
||||
// location's code signature, even though it's been moved aside.
|
||||
@interface SQRLInstallerOwnedBundle : MTLModel
|
||||
|
||||
// Designated initialiser.
|
||||
//
|
||||
// originalURL - Where the bundle currently resides, and should be restored to
|
||||
// should an error occur.
|
||||
// temporaryURL - Where the bundle will be moved to, so that another bundle can
|
||||
// take its place at originalURL.
|
||||
// codeSignature - The code signature of the original bundle, so that the
|
||||
// signature can be used irrespective of where the bundle
|
||||
// currently resides.
|
||||
//
|
||||
// Returns an initialised owned bundle for serializing.
|
||||
- (instancetype)initWithOriginalURL:(NSURL *)originalURL temporaryURL:(NSURL *)temporaryURL codeSignature:(SQRLCodeSignature *)codeSignature;
|
||||
|
||||
@property (readonly, copy, nonatomic) NSURL *originalURL;
|
||||
@property (readonly, copy, nonatomic) NSURL *temporaryURL;
|
||||
@property (readonly, copy, nonatomic) SQRLCodeSignature *codeSignature;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,23 @@
|
||||
//
|
||||
// SQRLInstallerOwnedBundle.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 08/01/2014.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLInstallerOwnedBundle.h"
|
||||
|
||||
#import "EXTKeyPathCoding.h"
|
||||
|
||||
@implementation SQRLInstallerOwnedBundle
|
||||
|
||||
- (instancetype)initWithOriginalURL:(NSURL *)originalURL temporaryURL:(NSURL *)temporaryURL codeSignature:(SQRLCodeSignature *)codeSignature {
|
||||
return [self initWithDictionary:@{
|
||||
@keypath(self.originalURL): originalURL,
|
||||
@keypath(self.temporaryURL): temporaryURL,
|
||||
@keypath(self.codeSignature): codeSignature,
|
||||
} error:NULL];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -10,6 +10,12 @@
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
// The domain for errors originating within SQRLShipItLauncher.
|
||||
extern NSString * const SQRLShipItLauncherErrorDomain;
|
||||
|
||||
// The ShipIt service could not be started.
|
||||
extern const NSInteger SQRLShipItLauncherErrorCouldNotStartService;
|
||||
|
||||
// Responsible for launching the ShipIt service to actually install an update.
|
||||
@interface SQRLShipItLauncher : NSObject
|
||||
|
||||
|
||||
@@ -13,13 +13,16 @@
|
||||
#import <Security/Security.h>
|
||||
#import <ServiceManagement/ServiceManagement.h>
|
||||
#import <launch.h>
|
||||
#import "Squirrel-Constants.h"
|
||||
#import "SQRLAuthorization.h"
|
||||
|
||||
NSString * const SQRLShipItLauncherErrorDomain = @"SQRLShipItLauncherErrorDomain";
|
||||
|
||||
const NSInteger SQRLShipItLauncherErrorCouldNotStartService = 1;
|
||||
|
||||
@implementation SQRLShipItLauncher
|
||||
|
||||
+ (NSString *)shipItJobLabel {
|
||||
NSString *currentAppIdentifier = NSBundle.mainBundle.bundleIdentifier ?: [NSString stringWithFormat:@"%@:%d", NSProcessInfo.processInfo.processName, NSProcessInfo.processInfo.processIdentifier];
|
||||
return [currentAppIdentifier stringByAppendingString:@".ShipIt"];
|
||||
return [SQRLDirectoryManager.currentApplicationManager.applicationIdentifier stringByAppendingString:@".ShipIt"];
|
||||
}
|
||||
|
||||
+ (RACSignal *)shipItJobDictionary {
|
||||
@@ -28,9 +31,9 @@
|
||||
return [[[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:jobLabel];
|
||||
return [directoryManager applicationSupportURL];
|
||||
return [RACSignal zip:@[ [directoryManager shipItStdoutURL], [directoryManager shipItStderrURL] ]];
|
||||
}]
|
||||
map:^(NSURL *appSupportURL) {
|
||||
reduceEach:^(NSURL *stdoutURL, NSURL *stderrURL) {
|
||||
NSBundle *squirrelBundle = [NSBundle bundleForClass:self.class];
|
||||
NSAssert(squirrelBundle != nil, @"Could not open Squirrel.framework bundle");
|
||||
|
||||
@@ -54,13 +57,9 @@
|
||||
[arguments addObject:jobLabel];
|
||||
|
||||
jobDict[@(LAUNCH_JOBKEY_PROGRAMARGUMENTS)] = arguments;
|
||||
jobDict[@(LAUNCH_JOBKEY_STANDARDOUTPATH)] = [appSupportURL URLByAppendingPathComponent:@"ShipIt_stdout.log"].path;
|
||||
jobDict[@(LAUNCH_JOBKEY_STANDARDERRORPATH)] = [appSupportURL URLByAppendingPathComponent:@"ShipIt_stderr.log"].path;
|
||||
jobDict[@(LAUNCH_JOBKEY_STANDARDOUTPATH)] = stdoutURL.path;
|
||||
jobDict[@(LAUNCH_JOBKEY_STANDARDERRORPATH)] = stderrURL.path;
|
||||
|
||||
#if DEBUG
|
||||
jobDict[@(LAUNCH_JOBKEY_DEBUG)] = @YES;
|
||||
#endif
|
||||
|
||||
return jobDict;
|
||||
}]
|
||||
setNameWithFormat:@"+shipItJobDictionary"];
|
||||
@@ -68,7 +67,7 @@
|
||||
|
||||
+ (RACSignal *)shipItAuthorization {
|
||||
return [[RACSignal
|
||||
createSignal:^(id<RACSubscriber> subscriber) {
|
||||
createSignal:^ RACDisposable * (id<RACSubscriber> subscriber) {
|
||||
AuthorizationItem rightItems[] = {
|
||||
{
|
||||
.name = kSMRightModifySystemDaemons,
|
||||
@@ -105,16 +104,15 @@
|
||||
|
||||
AuthorizationRef authorization = NULL;
|
||||
OSStatus authorizationError = AuthorizationCreate(&rights, &environment, kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights, &authorization);
|
||||
|
||||
if (authorizationError == noErr) {
|
||||
[subscriber sendNext:(__bridge id)authorization];
|
||||
[subscriber sendNext:[[SQRLAuthorization alloc] initWithAuthorization:authorization]];
|
||||
[subscriber sendCompleted];
|
||||
} else {
|
||||
[subscriber sendError:[NSError errorWithDomain:NSOSStatusErrorDomain code:authorizationError userInfo:nil]];
|
||||
}
|
||||
|
||||
return [RACDisposable disposableWithBlock:^{
|
||||
if (authorization != NULL) AuthorizationFree(authorization, kAuthorizationFlagDestroyRights);
|
||||
}];
|
||||
return nil;
|
||||
}]
|
||||
setNameWithFormat:@"+shipItAuthorization"];
|
||||
}
|
||||
@@ -124,22 +122,22 @@
|
||||
zip:@[
|
||||
self.shipItJobDictionary,
|
||||
(privileged ? self.shipItAuthorization : [RACSignal return:nil])
|
||||
] reduce:^(NSDictionary *jobDictionary, id authorization) {
|
||||
] reduce:^(NSDictionary *jobDictionary, SQRLAuthorization *authorizationValue) {
|
||||
CFStringRef domain = (privileged ? kSMDomainSystemLaunchd : kSMDomainUserLaunchd);
|
||||
|
||||
CFErrorRef cfError;
|
||||
if (!SMJobRemove(domain, (__bridge CFStringRef)self.shipItJobLabel, (__bridge AuthorizationRef)authorization, true, &cfError)) {
|
||||
#if DEBUG
|
||||
NSLog(@"Could not remove previous ShipIt job: %@", cfError);
|
||||
#endif
|
||||
AuthorizationRef authorization = authorizationValue.authorization;
|
||||
|
||||
if (cfError != NULL) {
|
||||
CFRelease(cfError);
|
||||
cfError = NULL;
|
||||
CFErrorRef cfError;
|
||||
if (!SMJobRemove(domain, (__bridge CFStringRef)self.shipItJobLabel, authorization, true, &cfError)) {
|
||||
NSError *error = CFBridgingRelease(cfError);
|
||||
cfError = NULL;
|
||||
|
||||
if (![error.domain isEqual:(__bridge id)kSMErrorDomainLaunchd] || error.code != kSMErrorJobNotFound) {
|
||||
NSLog(@"Could not remove previous ShipIt job: %@", error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!SMJobSubmit(domain, (__bridge CFDictionaryRef)jobDictionary, (__bridge AuthorizationRef)authorization, &cfError)) {
|
||||
if (!SMJobSubmit(domain, (__bridge CFDictionaryRef)jobDictionary, authorization, &cfError)) {
|
||||
return [RACSignal error:CFBridgingRelease(cfError)];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
//
|
||||
// SQRLShipItRequest.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 08/01/2014.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
// The domain for errors originating within `SQRLShipItRequest`.
|
||||
extern NSString * const SQRLShipItRequestErrorDomain;
|
||||
|
||||
// Errors originating from the `SQRLShipItRequestErrorDomain`.
|
||||
//
|
||||
// SQRLShipItRequestErrorMissingRequiredProperty - A required property was `nil`
|
||||
// upon initialization.
|
||||
//
|
||||
// The `userInfo` dictionary for
|
||||
// this error will contain
|
||||
// `SQRLShipItStatePropertyErrorKey`.
|
||||
//
|
||||
// SQRLShipItRequestErrorUnarchiving - The saved request could not
|
||||
// be unarchived, possibly
|
||||
// because it's invalid.
|
||||
//
|
||||
// SQRLShipItRequestErrorArchiving - The request object could not
|
||||
// be archived.
|
||||
typedef enum : NSInteger {
|
||||
SQRLShipItRequestErrorMissingRequiredProperty = 1,
|
||||
SQRLShipItRequestErrorUnarchiving = 2,
|
||||
SQRLShipItRequestErrorArchiving = 3,
|
||||
} SQRLShipItRequestError;
|
||||
|
||||
// Associated with an `NSString` indicating the required property key that did
|
||||
// not have a value upon initialization.
|
||||
extern NSString * const SQRLShipItRequestPropertyErrorKey;
|
||||
|
||||
// Constructed and written to disk for `ShipIt` to pick up. This represents a
|
||||
// single update request from the client's perspective.
|
||||
@interface SQRLShipItRequest : MTLModel
|
||||
|
||||
// Reads a `SQRLShipItState` from disk, at the location specified by the given
|
||||
// URL signal.
|
||||
//
|
||||
// URLSignal - Determines the file location to read from, the signal should send
|
||||
// an `NSURL` object then complete, or error. This must not be nil.
|
||||
//
|
||||
// Returns a signal which will synchronously send a `SQRLShipItRequest` then
|
||||
// complete, or error.
|
||||
+ (RACSignal *)readUsingURL:(RACSignal *)URLSignal;
|
||||
|
||||
// Writes the receiver to disk, at the location specified by the given URL
|
||||
// signal.
|
||||
//
|
||||
// URLSignal - Determines the file location to write to. The signal should send
|
||||
// an `NSURL` object then complete, or error. This must not be nil.
|
||||
//
|
||||
// Returns a signal which will synchronously complete or error.
|
||||
- (RACSignal *)writeUsingURL:(RACSignal *)URLSignal;
|
||||
|
||||
// Designated initialiser.
|
||||
//
|
||||
// updateBundleURL - The update bundle which will replace
|
||||
// targetBundleURL. Must not be nil.
|
||||
// targetBundleURL - Where the update should be installed, if a bundle
|
||||
// is already present, the update is checked for
|
||||
// suitability against this bundle. Must not be nil.
|
||||
// bundleIdentifier - The bundle identifier that the installer should
|
||||
// wait for instances of to terminate before
|
||||
// installing. Can be nil.
|
||||
// launchAfterInstallation - Whether the updated application should be launched
|
||||
// after installation.
|
||||
// useUpdateBundleName - Should the target use the update bundle's name?
|
||||
//
|
||||
// Returns a request which can be written to disk for ShipIt to read and
|
||||
// perform.
|
||||
- (instancetype)initWithUpdateBundleURL:(NSURL *)updateBundleURL targetBundleURL:(NSURL *)targetBundleURL bundleIdentifier:(NSString *)bundleIdentifier launchAfterInstallation:(BOOL)launchAfterInstallation useUpdateBundleName:(BOOL)useUpdateBundleName;
|
||||
|
||||
// The URL to the downloaded update's app bundle.
|
||||
@property (nonatomic, copy, readonly) NSURL *updateBundleURL;
|
||||
|
||||
// The URL to the app bundle that should be replaced with the update.
|
||||
@property (nonatomic, copy, readonly) NSURL *targetBundleURL;
|
||||
|
||||
// The bundle identifier of the application being updated.
|
||||
//
|
||||
// If not nil, the installer will wait for applications matching this identifier
|
||||
// (and `targetBundleURL`) to terminate before continuing.
|
||||
@property (nonatomic, copy, readonly) NSString *bundleIdentifier;
|
||||
|
||||
// Whether to launch the application after an update is successfully installed.
|
||||
@property (nonatomic, assign, readonly) BOOL launchAfterInstallation;
|
||||
|
||||
// Whether the app should use the update bundle's name.
|
||||
@property (nonatomic, assign, readonly) BOOL useUpdateBundleName;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,194 @@
|
||||
//
|
||||
// SQRLShipItRequest.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 08/01/2014.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLShipItRequest.h"
|
||||
|
||||
#import "EXTKeyPathCoding.h"
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
|
||||
NSString * const SQRLShipItRequestErrorDomain = @"SQRLShipItRequestErrorDomain";
|
||||
|
||||
NSString * const SQRLShipItRequestPropertyErrorKey = @"SQRLShipItRequestPropertyErrorKey";
|
||||
|
||||
@interface SQRLShipItRequest () <MTLJSONSerializing>
|
||||
@end
|
||||
|
||||
@implementation SQRLShipItRequest
|
||||
|
||||
#pragma mark Lifecycle
|
||||
|
||||
- (id)initWithDictionary:(NSDictionary *)dictionary error:(NSError **)error {
|
||||
self = [super initWithDictionary:dictionary error:error];
|
||||
if (self == nil) return nil;
|
||||
|
||||
BOOL (^validateKey)(NSString *) = ^(NSString *key) {
|
||||
if ([self valueForKey:key] != nil) return YES;
|
||||
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Missing required value", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:NSLocalizedString(@"\"%@\" must not be set to nil.", nil), key]
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:SQRLShipItRequestErrorDomain code:SQRLShipItRequestErrorMissingRequiredProperty userInfo:userInfo];
|
||||
}
|
||||
|
||||
return NO;
|
||||
};
|
||||
|
||||
if (!validateKey(@keypath(self.targetBundleURL))) return nil;
|
||||
if (!validateKey(@keypath(self.updateBundleURL))) return nil;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (instancetype)initWithUpdateBundleURL:(NSURL *)updateBundleURL targetBundleURL:(NSURL *)targetBundleURL bundleIdentifier:(NSString *)bundleIdentifier launchAfterInstallation:(BOOL)launchAfterInstallation useUpdateBundleName:(BOOL)useUpdateBundleName {
|
||||
return [self initWithDictionary:@{
|
||||
@keypath(self.updateBundleURL): updateBundleURL,
|
||||
@keypath(self.targetBundleURL): targetBundleURL,
|
||||
@keypath(self.bundleIdentifier): bundleIdentifier ?: NSNull.null,
|
||||
@keypath(self.launchAfterInstallation): @(launchAfterInstallation),
|
||||
@keypath(self.useUpdateBundleName): @(useUpdateBundleName),
|
||||
} error:NULL];
|
||||
}
|
||||
|
||||
#pragma mark Serialization
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
return @{};
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)updateBundleURLJSONTransformer {
|
||||
return [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)targetBundleURLJSONTransformer {
|
||||
return [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
|
||||
}
|
||||
|
||||
+ (RACSignal *)readUsingURL:(RACSignal *)URL {
|
||||
NSParameterAssert(URL != nil);
|
||||
|
||||
return [[[[URL
|
||||
flattenMap:^(NSURL *stateURL) {
|
||||
NSError *error;
|
||||
NSData *data = [self readFromURL:stateURL error:&error];
|
||||
if (data == nil) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
return [RACSignal return:data];
|
||||
}]
|
||||
flattenMap:^(NSData *data) {
|
||||
return [self readFromData:data];
|
||||
}]
|
||||
catch:^(NSError *error) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not read update request", nil),
|
||||
};
|
||||
if (error != nil) {
|
||||
userInfo = [userInfo mtl_dictionaryByAddingEntriesFromDictionary:@{
|
||||
NSUnderlyingErrorKey: error,
|
||||
}];
|
||||
}
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLShipItRequestErrorDomain code:SQRLShipItRequestErrorUnarchiving userInfo:userInfo]];
|
||||
}]
|
||||
setNameWithFormat:@"+readUsingURL: %@", URL];
|
||||
}
|
||||
|
||||
+ (NSData *)readFromURL:(NSURL *)URL error:(NSError **)errorRef {
|
||||
__block NSData *data = nil;
|
||||
|
||||
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
|
||||
[coordinator coordinateReadingItemAtURL:URL options:NSFileCoordinatorReadingWithoutChanges error:errorRef byAccessor:^(NSURL *newURL) {
|
||||
data = [NSData dataWithContentsOfURL:newURL options:NSDataReadingUncached error:errorRef];
|
||||
}];
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
+ (RACSignal *)readFromData:(NSData *)data {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
NSError *error;
|
||||
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
|
||||
if (JSONDictionary == nil) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
SQRLShipItRequest *request = [MTLJSONAdapter modelOfClass:SQRLShipItRequest.class fromJSONDictionary:JSONDictionary error:&error];
|
||||
if (request == nil) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
return [RACSignal return:request];
|
||||
|
||||
}]
|
||||
setNameWithFormat:@"+readFromData: <NSData %p>", data];
|
||||
}
|
||||
|
||||
- (RACSignal *)writeUsingURL:(RACSignal *)URL {
|
||||
NSParameterAssert(URL != nil);
|
||||
|
||||
return [[[[RACSignal
|
||||
zip:@[
|
||||
URL,
|
||||
[self serialization]
|
||||
] reduce:^(NSURL *stateURL, NSData *data) {
|
||||
NSError *error;
|
||||
BOOL write = [self writeData:data toURL:stateURL error:&error];
|
||||
if (!write) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
flatten]
|
||||
catch:^(NSError *error) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not write update request", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"An unknown error occurred while archiving.", nil),
|
||||
};
|
||||
if (error != nil) {
|
||||
userInfo = [userInfo mtl_dictionaryByAddingEntriesFromDictionary:@{
|
||||
NSUnderlyingErrorKey: error,
|
||||
}];
|
||||
}
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLShipItRequestErrorDomain code:SQRLShipItRequestErrorArchiving userInfo:userInfo]];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -writeUsingURL: %@", self, URL];
|
||||
}
|
||||
|
||||
- (BOOL)writeData:(NSData *)data toURL:(NSURL *)URL error:(NSError **)errorRef {
|
||||
__block BOOL success = NO;
|
||||
|
||||
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
|
||||
[coordinator coordinateWritingItemAtURL:URL options:0 error:errorRef byAccessor:^(NSURL *newURL) {
|
||||
success = [data writeToURL:newURL options:NSDataWritingAtomic error:errorRef];
|
||||
}];
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
- (RACSignal *)serialization {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
NSDictionary *JSONDictionary = [MTLJSONAdapter JSONDictionaryFromModel:self];
|
||||
|
||||
NSError *error;
|
||||
NSData *data = [NSJSONSerialization dataWithJSONObject:JSONDictionary options:0 error:&error];
|
||||
if (data == nil) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
return [RACSignal return:data];
|
||||
}]
|
||||
setNameWithFormat:@"%@ serialization", self];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,105 +0,0 @@
|
||||
//
|
||||
// SQRLShipItState.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-10-08.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
|
||||
// Associated with an NSString indicating the required property key that did not
|
||||
// have a value upon initialization.
|
||||
extern NSString * const SQRLShipItStatePropertyErrorKey;
|
||||
|
||||
// The current state of the installer, for persistence across relaunches and for
|
||||
// tolerance of system failures.
|
||||
//
|
||||
// SQRLInstallerStateNothingToDo - ShipIt has not started installing yet.
|
||||
// SQRLInstallerStateClearingQuarantine - Clearing the quarantine flag on the
|
||||
// update bundle so it can used without
|
||||
// issue.
|
||||
// SQRLInstallerStateBackingUp - Backing up the target bundle so it can
|
||||
// be restored in the event of failure.
|
||||
// SQRLInstallerStateInstalling - Replacing the target bundle with the
|
||||
// update bundle.
|
||||
// SQRLInstallerStateVerifyingInPlace - Verifying that the target bundle is
|
||||
// still valid after updating.
|
||||
// SQRLInstallerStateRelaunching - Relaunching the updated application.
|
||||
// This state will be entered even if
|
||||
// there's no relaunching to do.
|
||||
//
|
||||
// Note that these values must remain backwards compatible, so ShipIt doesn't
|
||||
// start up in a weird mode on a newer version.
|
||||
typedef enum : NSInteger {
|
||||
SQRLInstallerStateNothingToDo = 0,
|
||||
SQRLInstallerStateClearingQuarantine,
|
||||
SQRLInstallerStateBackingUp,
|
||||
SQRLInstallerStateInstalling,
|
||||
SQRLInstallerStateVerifyingInPlace,
|
||||
SQRLInstallerStateRelaunching
|
||||
} SQRLInstallerState;
|
||||
|
||||
@class RACSignal;
|
||||
@class SQRLCodeSignature;
|
||||
|
||||
// Encapsulates all the state needed by the ShipIt process.
|
||||
@interface SQRLShipItState : MTLModel
|
||||
|
||||
// Reads a `SQRLShipItState` from disk, at the location specified by the given
|
||||
// URL signal.
|
||||
//
|
||||
// URLSignal - Determines the file location to read from, the signal should send
|
||||
// an `NSURL` object then complete, or error. This must not be nil.
|
||||
//
|
||||
// Returns a signal which will synchronously send a `SQRLShipItState` then
|
||||
// complete, or error.
|
||||
+ (RACSignal *)readUsingURL:(RACSignal *)URL;
|
||||
|
||||
// Initializes the receiver with the arguments that will not change during
|
||||
// installation.
|
||||
- (id)initWithTargetBundleURL:(NSURL *)targetBundleURL updateBundleURL:(NSURL *)updateBundleURL bundleIdentifier:(NSString *)bundleIdentifier codeSignature:(SQRLCodeSignature *)codeSignature;
|
||||
|
||||
// Writes the receiver to disk, at the location specified by the given URL
|
||||
// signal.
|
||||
//
|
||||
// URL - Determines the file location to write to. The signal should send an
|
||||
// `NSURL` object then complete, or error. This must not be nil.
|
||||
//
|
||||
// Returns a signal which will synchronously complete or error.
|
||||
- (RACSignal *)writeUsingURL:(RACSignal *)URL;
|
||||
|
||||
// The URL to the app bundle that should be replaced with an update.
|
||||
@property (nonatomic, copy, readonly) NSURL *targetBundleURL;
|
||||
|
||||
// The URL to the downloaded update's app bundle.
|
||||
@property (nonatomic, copy, readonly) NSURL *updateBundleURL;
|
||||
|
||||
// A code signature that the update bundle must match in order to be valid.
|
||||
@property (nonatomic, copy, readonly) SQRLCodeSignature *codeSignature;
|
||||
|
||||
// The bundle identifier of the application being updated.
|
||||
//
|
||||
// If not nil, the installer will wait for applications matching this identifier
|
||||
// (and `targetBundleURL`) to terminate before continuing.
|
||||
@property (nonatomic, copy, readonly) NSString *bundleIdentifier;
|
||||
|
||||
// The current state of the installer.
|
||||
@property (atomic, assign) SQRLInstallerState installerState;
|
||||
|
||||
// The number of installation attempts that have occurred for the current
|
||||
// `state`.
|
||||
@property (atomic, assign) NSUInteger installationStateAttempt;
|
||||
|
||||
// Whether to relaunch the application after an update is successfully
|
||||
// installed.
|
||||
@property (atomic, assign) BOOL relaunchAfterInstallation;
|
||||
|
||||
// The URL where the target bundle has been backed up to before installing the
|
||||
// update.
|
||||
//
|
||||
// This property is set automatically during the course of installation. It
|
||||
// should not be preset.
|
||||
@property (atomic, copy) NSURL *backupBundleURL;
|
||||
|
||||
@end
|
||||
@@ -1,118 +0,0 @@
|
||||
//
|
||||
// SQRLShipItState.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-10-08.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLShipItState.h"
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import "Squirrel-Constants.h"
|
||||
|
||||
NSString * const SQRLShipItStatePropertyErrorKey = @"SQRLShipItStatePropertyErrorKey";
|
||||
|
||||
@implementation SQRLShipItState
|
||||
|
||||
#pragma mark Lifecycle
|
||||
|
||||
- (id)initWithDictionary:(NSDictionary *)dictionary error:(NSError **)error {
|
||||
self = [super initWithDictionary:dictionary error:error];
|
||||
if (self == nil) return nil;
|
||||
|
||||
BOOL (^validateKey)(NSString *) = ^(NSString *key) {
|
||||
if ([self valueForKey:key] != nil) return YES;
|
||||
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Missing required value", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:NSLocalizedString(@"\"%@\" must not be set to nil.", nil), key]
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:SQRLErrorDomain code:SQRLShipItStateErrorMissingRequiredProperty userInfo:userInfo];
|
||||
}
|
||||
|
||||
return NO;
|
||||
};
|
||||
|
||||
if (!validateKey(@keypath(self.targetBundleURL))) return nil;
|
||||
if (!validateKey(@keypath(self.updateBundleURL))) return nil;
|
||||
if (!validateKey(@keypath(self.codeSignature))) return nil;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)initWithTargetBundleURL:(NSURL *)targetBundleURL updateBundleURL:(NSURL *)updateBundleURL bundleIdentifier:(NSString *)bundleIdentifier codeSignature:(SQRLCodeSignature *)codeSignature {
|
||||
return [self initWithDictionary:@{
|
||||
@keypath(self.targetBundleURL): targetBundleURL,
|
||||
@keypath(self.updateBundleURL): updateBundleURL,
|
||||
@keypath(self.bundleIdentifier): bundleIdentifier ?: NSNull.null,
|
||||
@keypath(self.codeSignature): codeSignature,
|
||||
} error:NULL];
|
||||
}
|
||||
|
||||
#pragma mark Serialization
|
||||
|
||||
+ (RACSignal *)readUsingURL:(RACSignal *)URL {
|
||||
NSParameterAssert(URL != nil);
|
||||
|
||||
return [[[URL
|
||||
flattenMap:^(NSURL *stateURL) {
|
||||
NSError *error = nil;
|
||||
NSData *data = [NSData dataWithContentsOfURL:stateURL options:NSDataReadingUncached error:&error];
|
||||
if (data == nil) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
return [RACSignal return:data];
|
||||
}]
|
||||
flattenMap:^(NSData *data) {
|
||||
SQRLShipItState *state = [NSKeyedUnarchiver unarchiveObjectWithData:data];
|
||||
if (![state isKindOfClass:SQRLShipItState.class]) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not read saved state", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"An unknown error occurred while unarchiving.", nil)
|
||||
};
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLErrorDomain code:SQRLShipItStateErrorUnarchiving userInfo:userInfo]];
|
||||
}
|
||||
|
||||
return [RACSignal return:state];
|
||||
}]
|
||||
setNameWithFormat:@"+readUsingURL: %@", URL];
|
||||
}
|
||||
|
||||
- (RACSignal *)writeUsingURL:(RACSignal *)URL {
|
||||
NSParameterAssert(URL != nil);
|
||||
|
||||
RACSignal *serialization = [RACSignal defer:^{
|
||||
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
|
||||
if (data == nil) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not save state", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"An unknown error occurred while archiving.", nil)
|
||||
};
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLErrorDomain code:SQRLShipItStateErrorArchiving userInfo:userInfo]];
|
||||
}
|
||||
|
||||
return [RACSignal return:data];
|
||||
}];
|
||||
|
||||
return [[[RACSignal
|
||||
zip:@[
|
||||
URL,
|
||||
serialization
|
||||
] reduce:^(NSURL *stateURL, NSData *data) {
|
||||
NSError *error = nil;
|
||||
if (![data writeToURL:stateURL options:NSDataWritingAtomic error:&error]) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
flatten]
|
||||
setNameWithFormat:@"%@ -writeUsingURL: %@", self, URL];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -6,7 +6,7 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
|
||||
@@ -7,7 +7,14 @@
|
||||
//
|
||||
|
||||
#import "SQRLTerminationListener.h"
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
|
||||
#import "EXTKeyPathCoding.h"
|
||||
#import <ReactiveCocoa/NSArray+RACSequenceAdditions.h>
|
||||
#import <ReactiveCocoa/RACDisposable.h>
|
||||
#import <ReactiveCocoa/RACScheduler.h>
|
||||
#import <ReactiveCocoa/RACSequence.h>
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
#import <ReactiveCocoa/RACSubscriber.h>
|
||||
|
||||
@interface SQRLTerminationListener ()
|
||||
|
||||
@@ -74,7 +81,6 @@
|
||||
dispatch_resume(source);
|
||||
return [RACDisposable disposableWithBlock:^{
|
||||
dispatch_source_cancel(source);
|
||||
dispatch_release(source);
|
||||
}];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -waitForTerminationOfProcessIdentifier: %i", self, (int)processIdentifier];
|
||||
|
||||
+17
-3
@@ -74,7 +74,7 @@ NSString * const SQRLUpdateJSONPublicationDateKey = @"pub_date";
|
||||
|
||||
+ (NSValueTransformer *)releaseDateJSONTransformer {
|
||||
// ISO 8601 Time Zone with ':'
|
||||
NSString * const ISO8601DateFormat = @"yyyy'-'MM'-'DD'T'HH':'mm':'ssZZZZZ";
|
||||
NSString * const ISO8601DateFormat = @"yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ";
|
||||
|
||||
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^ NSDate * (NSString *dateString) {
|
||||
if (![dateString isKindOfClass:NSString.class]) return nil;
|
||||
@@ -134,19 +134,33 @@ NSString * const SQRLUpdateJSONPublicationDateKey = @"pub_date";
|
||||
|
||||
- (BOOL)validateUpdateURL:(NSURL **)updateURLPtr error:(NSError **)error {
|
||||
NSURL *updateURL = *updateURLPtr;
|
||||
if (![updateURL isKindOfClass:NSURL.class] || updateURL.scheme == nil || updateURL.host == nil || updateURL.path == nil) {
|
||||
if (![updateURL isKindOfClass:NSURL.class]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Validation failed", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:NSLocalizedString(@"An invalid updateURL was given to SQRLUpdate: %@", nil), updateURL]
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSKeyValueValidationError userInfo:userInfo];
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
BOOL valid = (updateURL.scheme != nil);
|
||||
valid &= ([updateURL.scheme isEqualToString:@"file"] || updateURL.host != nil);
|
||||
valid &= (updateURL.path != nil);
|
||||
if (!valid) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Validation failed", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Update URLs must have a scheme, a host and a path: %@", nil), updateURL]
|
||||
};
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSKeyValueValidationError userInfo:userInfo];
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
+66
-5
@@ -6,6 +6,52 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
|
||||
// Represents the current state of the updater.
|
||||
//
|
||||
// SQRLUpdaterStateIdle - Doing absolutely diddly squat.
|
||||
// SQRLUpdaterStateCheckingForUpdate - Checking for any updates from the server.
|
||||
// SQRLUpdaterStateDownloadingUpdate - Update found, downloading the archive.
|
||||
// SQRLUpdaterStateAwaitingRelaunch - Awaiting a relaunch to install
|
||||
// the update.
|
||||
typedef enum : NSUInteger {
|
||||
SQRLUpdaterStateIdle,
|
||||
SQRLUpdaterStateCheckingForUpdate,
|
||||
SQRLUpdaterStateDownloadingUpdate,
|
||||
SQRLUpdaterStateAwaitingRelaunch,
|
||||
} SQRLUpdaterState;
|
||||
|
||||
// The domain for errors originating within SQRLUpdater.
|
||||
extern NSString * const SQRLUpdaterErrorDomain;
|
||||
|
||||
// The downloaded update does not contain an app bundle, or it was deleted on
|
||||
// disk before we could get to it.
|
||||
extern const NSInteger SQRLUpdaterErrorMissingUpdateBundle;
|
||||
|
||||
// An error occurred in the out-of-process updater while it was setting up.
|
||||
extern const NSInteger SQRLUpdaterErrorPreparingUpdateJob;
|
||||
|
||||
// The code signing requirement for the running application could not be
|
||||
// retrieved.
|
||||
extern const NSInteger SQRLUpdaterErrorRetrievingCodeSigningRequirement;
|
||||
|
||||
// The server sent a response that we didn't understand.
|
||||
//
|
||||
// Includes `SQRLUpdaterServerDataErrorKey` in the error's `userInfo`.
|
||||
extern const NSInteger SQRLUpdaterErrorInvalidServerResponse;
|
||||
|
||||
// The server sent a response body that we didn't understand.
|
||||
//
|
||||
// Includes `SQRLUpdaterServerDataErrorKey` in the error's `userInfo`.
|
||||
extern const NSInteger SQRLUpdaterErrorInvalidServerBody;
|
||||
|
||||
// The server sent update JSON that we didn't understand.
|
||||
//
|
||||
// Includes `SQRLUpdaterJSONObjectErrorKey` in the error's `userInfo`.
|
||||
extern const NSInteger SQRLUpdaterErrorInvalidJSON;
|
||||
|
||||
// Associated with the `NSData` received from the server when an error with code
|
||||
// `SQRLUpdaterErrorInvalidServerResponse` is generated.
|
||||
extern NSString * const SQRLUpdaterServerDataErrorKey;
|
||||
@@ -26,6 +72,11 @@ extern NSString * const SQRLUpdaterJSONObjectErrorKey;
|
||||
// If an update is available, it will be sent on `updates` once downloaded.
|
||||
@property (nonatomic, strong, readonly) RACCommand *checkForUpdatesCommand;
|
||||
|
||||
// The current state of the manager.
|
||||
//
|
||||
// This property is KVO-compliant.
|
||||
@property (atomic, readonly) SQRLUpdaterState state;
|
||||
|
||||
// Sends an `SQRLDownloadedUpdate` object on the main thread whenever a new
|
||||
// update is available.
|
||||
//
|
||||
@@ -33,11 +84,6 @@ extern NSString * const SQRLUpdaterJSONObjectErrorKey;
|
||||
// flattened for convenience.
|
||||
@property (nonatomic, strong, readonly) RACSignal *updates;
|
||||
|
||||
// Whether or not to relaunch after installing an update.
|
||||
//
|
||||
// This will be reset to NO whenever update installation fails.
|
||||
@property (atomic) BOOL shouldRelaunch;
|
||||
|
||||
// The request that will be sent to check for updates.
|
||||
//
|
||||
// The default value is the argument that was originally passed to
|
||||
@@ -75,6 +121,21 @@ extern NSString * const SQRLUpdaterJSONObjectErrorKey;
|
||||
// checking.
|
||||
- (RACDisposable *)startAutomaticChecksWithInterval:(NSTimeInterval)interval;
|
||||
|
||||
// Terminates the running application to install any available update, then
|
||||
// automatically relaunches the app after updating.
|
||||
//
|
||||
// This method is only useful if you want the application to automatically
|
||||
// relaunch. Otherwise, you can simply use `-[NSApplication terminate:]` or any
|
||||
// other exit mechanism.
|
||||
//
|
||||
// After invoking this method, the receiver is responsible for terminating the
|
||||
// application upon success. The app must not be terminated in any other way
|
||||
// unless an error occurs.
|
||||
//
|
||||
// Returns a signal that will error on the main scheduler if anything goes
|
||||
// wrong before termination. The signal will never complete.
|
||||
- (RACSignal *)relaunchToInstallUpdate;
|
||||
|
||||
@end
|
||||
|
||||
@interface SQRLUpdater (Unavailable)
|
||||
|
||||
+228
-44
@@ -15,18 +15,35 @@
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLDownloadedUpdate.h"
|
||||
#import "SQRLShipItLauncher.h"
|
||||
#import "SQRLShipItState.h"
|
||||
#import "SQRLUpdate.h"
|
||||
#import "SQRLZipArchiver.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import "Squirrel-Constants.h"
|
||||
|
||||
NSString * const SQRLUpdaterErrorDomain = @"SQRLUpdaterErrorDomain";
|
||||
NSString * const SQRLUpdaterServerDataErrorKey = @"SQRLUpdaterServerDataErrorKey";
|
||||
NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey";
|
||||
|
||||
const NSInteger SQRLUpdaterErrorMissingUpdateBundle = 2;
|
||||
const NSInteger SQRLUpdaterErrorPreparingUpdateJob = 3;
|
||||
const NSInteger SQRLUpdaterErrorRetrievingCodeSigningRequirement = 4;
|
||||
const NSInteger SQRLUpdaterErrorInvalidServerResponse = 5;
|
||||
const NSInteger SQRLUpdaterErrorInvalidJSON = 6;
|
||||
const NSInteger SQRLUpdaterErrorInvalidServerBody = 7;
|
||||
|
||||
// The prefix used when creating temporary directories for updates. This will be
|
||||
// followed by a random string of characters.
|
||||
static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
|
||||
@interface SQRLUpdater ()
|
||||
|
||||
@property (atomic, readwrite) SQRLUpdaterState state;
|
||||
|
||||
/// The etag of the currently downloaded update, nil if no update has been
|
||||
/// downloaded.
|
||||
@property (atomic, copy) NSString *etag;
|
||||
|
||||
// The code signature for the running application, used to check updates before
|
||||
// sending them to ShipIt.
|
||||
@property (nonatomic, strong, readonly) SQRLCodeSignature *signature;
|
||||
@@ -133,11 +150,19 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
|
||||
NSError *error = nil;
|
||||
_signature = [SQRLCodeSignature currentApplicationSignature:&error];
|
||||
NSAssert(_signature != nil, @"Could not get code signature for running application: %@", error);
|
||||
if (_signature == nil) {
|
||||
#if DEBUG
|
||||
NSLog(@"Could not get code signature for running application, application updates are disabled: %@", error);
|
||||
return nil;
|
||||
#else
|
||||
NSDictionary *exceptionInfo = @{ NSUnderlyingErrorKey: error };
|
||||
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Could not get code signature for running application" userInfo:exceptionInfo];
|
||||
#endif
|
||||
}
|
||||
|
||||
BOOL updatesDisabled = (getenv("DISABLE_UPDATE_CHECK") != NULL);
|
||||
|
||||
@weakify(self);
|
||||
|
||||
_checkForUpdatesCommand = [[RACCommand alloc] initWithEnabled:[RACSignal return:@(!updatesDisabled)] signalBlock:^(id _) {
|
||||
@strongify(self);
|
||||
NSParameterAssert(self.updateRequest != nil);
|
||||
@@ -146,19 +171,51 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
NSMutableURLRequest *request = [self.updateRequest mutableCopy];
|
||||
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
|
||||
|
||||
return [[[[[[NSURLConnection
|
||||
rac_sendAsynchronousRequest:request]
|
||||
reduceEach:^(id _, NSData *data) {
|
||||
return data;
|
||||
return [[[[[[[[self
|
||||
performHousekeeping]
|
||||
then:^{
|
||||
self.state = SQRLUpdaterStateCheckingForUpdate;
|
||||
|
||||
return [NSURLConnection rac_sendAsynchronousRequest:request];
|
||||
}]
|
||||
reduceEach:^(NSURLResponse *response, NSData *bodyData) {
|
||||
if ([response isKindOfClass:NSHTTPURLResponse.class]) {
|
||||
NSHTTPURLResponse *httpResponse = (id)response;
|
||||
if (!(httpResponse.statusCode >= 200 && httpResponse.statusCode <= 299)) {
|
||||
NSDictionary *errorInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Update check failed", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"The server sent an invalid response. Try again later.", nil),
|
||||
SQRLUpdaterServerDataErrorKey: bodyData,
|
||||
};
|
||||
NSError *error = [NSError errorWithDomain:SQRLUpdaterErrorDomain code:SQRLUpdaterErrorInvalidServerResponse userInfo:errorInfo];
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
if (httpResponse.statusCode == 204 /* No Content */) {
|
||||
return [RACSignal empty];
|
||||
}
|
||||
}
|
||||
|
||||
return [RACSignal return:bodyData];
|
||||
}]
|
||||
flatten]
|
||||
flattenMap:^(NSData *data) {
|
||||
return [self updateFromJSONData:data];
|
||||
}]
|
||||
flattenMap:^(SQRLUpdate *update) {
|
||||
return [self downloadAndPrepareUpdate:update];
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
self.state = SQRLUpdaterStateDownloadingUpdate;
|
||||
|
||||
return [self downloadAndPrepareUpdate:update];
|
||||
}]
|
||||
doCompleted:^{
|
||||
self.state = SQRLUpdaterStateAwaitingRelaunch;
|
||||
}];
|
||||
}]
|
||||
doError:^(id _) {
|
||||
self.shouldRelaunch = NO;
|
||||
finally:^{
|
||||
if (self.state == SQRLUpdaterStateAwaitingRelaunch) return;
|
||||
self.state = SQRLUpdaterStateIdle;
|
||||
}]
|
||||
deliverOn:RACScheduler.mainThreadScheduler];
|
||||
}];
|
||||
@@ -216,7 +273,7 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
userInfo[SQRLUpdaterServerDataErrorKey] = data;
|
||||
if (error != nil) userInfo[NSUnderlyingErrorKey] = error;
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLErrorDomain code:SQRLUpdaterErrorInvalidServerResponse userInfo:userInfo]];
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLUpdaterErrorDomain code:SQRLUpdaterErrorInvalidServerBody userInfo:userInfo]];
|
||||
}
|
||||
|
||||
Class updateClass = self.updateClass;
|
||||
@@ -233,7 +290,7 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
userInfo[SQRLUpdaterJSONObjectErrorKey] = JSON;
|
||||
if (error != nil) userInfo[NSUnderlyingErrorKey] = error;
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLErrorDomain code:SQRLUpdaterErrorInvalidJSON userInfo:userInfo]];
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLUpdaterErrorDomain code:SQRLUpdaterErrorInvalidJSON userInfo:userInfo]];
|
||||
}
|
||||
|
||||
return [RACSignal return:update];
|
||||
@@ -271,12 +328,36 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
NSURL *zipDownloadURL = update.updateURL;
|
||||
NSMutableURLRequest *zipDownloadRequest = [NSMutableURLRequest requestWithURL:zipDownloadURL];
|
||||
[zipDownloadRequest setValue:@"application/zip" forHTTPHeaderField:@"Accept"];
|
||||
if (self.etag != nil) {
|
||||
[zipDownloadRequest setValue:self.etag forHTTPHeaderField:@"If-None-Match"];
|
||||
}
|
||||
|
||||
return [[[NSURLConnection
|
||||
return [[[[NSURLConnection
|
||||
rac_sendAsynchronousRequest:zipDownloadRequest]
|
||||
reduceEach:^(id _, NSData *data) {
|
||||
return data;
|
||||
reduceEach:^(NSURLResponse *response, NSData *bodyData) {
|
||||
if ([response isKindOfClass:NSHTTPURLResponse.class]) {
|
||||
NSHTTPURLResponse *httpResponse = (id)response;
|
||||
|
||||
if (httpResponse.statusCode == 304 /* Not Modified */) {
|
||||
return [RACSignal empty];
|
||||
}
|
||||
|
||||
if (!(httpResponse.statusCode >= 200 && httpResponse.statusCode <= 299)) {
|
||||
NSDictionary *errorInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Update download failed", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"The server sent an invalid response. Try again later.", nil),
|
||||
SQRLUpdaterServerDataErrorKey: bodyData,
|
||||
};
|
||||
NSError *error = [NSError errorWithDomain:SQRLUpdaterErrorDomain code:SQRLUpdaterErrorInvalidServerResponse userInfo:errorInfo];
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
self.etag = httpResponse.allHeaderFields[@"ETag"];
|
||||
}
|
||||
|
||||
return [RACSignal return:bodyData];
|
||||
}]
|
||||
flatten]
|
||||
flattenMap:^(NSData *data) {
|
||||
NSURL *zipOutputURL = [downloadDirectory URLByAppendingPathComponent:zipDownloadURL.lastPathComponent];
|
||||
|
||||
@@ -292,7 +373,14 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
NSLog(@"Download completed to: %@", zipOutputURL);
|
||||
}]
|
||||
flattenMap:^(NSURL *zipOutputURL) {
|
||||
return [SQRLZipArchiver unzipArchiveAtURL:zipOutputURL intoDirectoryAtURL:downloadDirectory];
|
||||
return [[SQRLZipArchiver
|
||||
unzipArchiveAtURL:zipOutputURL intoDirectoryAtURL:downloadDirectory]
|
||||
doCompleted:^{
|
||||
NSError *error = nil;
|
||||
if (![NSFileManager.defaultManager removeItemAtURL:zipOutputURL error:&error]) {
|
||||
NSLog(@"Error removing downloaded archive at %@: %@", zipOutputURL, error.sqrl_verboseDescription);
|
||||
}
|
||||
}];
|
||||
}]
|
||||
then:^{
|
||||
return [self updateBundleMatchingCurrentApplicationInDirectory:downloadDirectory];
|
||||
@@ -306,10 +394,10 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
return [[[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItLauncher.shipItJobLabel];
|
||||
return [directoryManager applicationSupportURL];
|
||||
return [directoryManager storageURL];
|
||||
}]
|
||||
flattenMap:^(NSURL *appSupportURL) {
|
||||
NSURL *updateDirectoryTemplate = [appSupportURL URLByAppendingPathComponent:@"update.XXXXXXX"];
|
||||
flattenMap:^(NSURL *storageURL) {
|
||||
NSURL *updateDirectoryTemplate = [storageURL URLByAppendingPathComponent:[SQRLUpdaterUniqueTemporaryDirectoryPrefix stringByAppendingString:@"XXXXXXX"]];
|
||||
char *updateDirectoryCString = strdup(updateDirectoryTemplate.path.fileSystemRepresentation);
|
||||
@onExit {
|
||||
free(updateDirectoryCString);
|
||||
@@ -369,7 +457,7 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"Could not locate update bundle for %@ within %@", nil), NSRunningApplication.currentApplication.bundleIdentifier, directory],
|
||||
};
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLErrorDomain code:SQRLUpdaterErrorMissingUpdateBundle userInfo:userInfo]];
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLUpdaterErrorDomain code:SQRLUpdaterErrorMissingUpdateBundle userInfo:userInfo]];
|
||||
}
|
||||
}]
|
||||
map:^(NSURL *URL) {
|
||||
@@ -378,6 +466,96 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
setNameWithFormat:@"%@ -applicationBundleMatchingCurrentApplicationInDirectory: %@", self, directory];
|
||||
}
|
||||
|
||||
- (RACSignal *)shipItStateURL {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItLauncher.shipItJobLabel];
|
||||
return directoryManager.shipItStateURL;
|
||||
}]
|
||||
setNameWithFormat:@"%@ -shipItStateURL", self];
|
||||
}
|
||||
|
||||
- (RACSignal *)performHousekeeping {
|
||||
return [[RACSignal
|
||||
merge:@[ [self pruneUpdateDirectories], [self truncateLogs] ]]
|
||||
catch:^(NSError *error) {
|
||||
NSLog(@"Error doing housekeeping: %@", error);
|
||||
return [RACSignal empty];
|
||||
}];
|
||||
}
|
||||
|
||||
/// Lazily removes outdated temporary directories (used for previous updates)
|
||||
/// upon subscription.
|
||||
///
|
||||
/// Pruning directories while an update is pending or in progress will result in
|
||||
/// undefined behavior.
|
||||
///
|
||||
/// Sends each removed directory then completes, or errors, on an unspecified
|
||||
/// thread.
|
||||
- (RACSignal *)pruneUpdateDirectories {
|
||||
return [[[RACSignal
|
||||
defer:^{
|
||||
// If we already have updates downloaded we don't wanna prune them.
|
||||
if (self.state == SQRLUpdaterStateAwaitingRelaunch) return [RACSignal empty];
|
||||
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItLauncher.shipItJobLabel];
|
||||
return [directoryManager storageURL];
|
||||
}]
|
||||
flattenMap:^(NSURL *storageURL) {
|
||||
NSFileManager *manager = [[NSFileManager alloc] init];
|
||||
NSDirectoryEnumerator *enumerator = [manager enumeratorAtURL:storageURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsSubdirectoryDescendants errorHandler:^(NSURL *URL, NSError *error) {
|
||||
NSLog(@"Error enumerating item %@ within directory %@: %@", URL, storageURL, error);
|
||||
return YES;
|
||||
}];
|
||||
|
||||
return [[enumerator.rac_sequence.signal
|
||||
filter:^(NSURL *enumeratedURL) {
|
||||
NSString *name = enumeratedURL.lastPathComponent;
|
||||
return [name hasPrefix:SQRLUpdaterUniqueTemporaryDirectoryPrefix];
|
||||
}]
|
||||
doNext:^(NSURL *directoryURL) {
|
||||
NSError *error = nil;
|
||||
if (![manager removeItemAtURL:directoryURL error:&error]) {
|
||||
NSLog(@"Error removing old update directory at %@: %@", directoryURL, error.sqrl_verboseDescription);
|
||||
}
|
||||
}];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -prunedUpdateDirectories", self];
|
||||
}
|
||||
|
||||
|
||||
// Like truncation, but backwards.
|
||||
- (RACSignal *)backwardTruncateFile:(NSURL *)fileURL {
|
||||
return [RACSignal defer:^{
|
||||
static const NSInteger MAX_LENGTH = 1024 * 1024 * 8;
|
||||
|
||||
NSError *error;
|
||||
NSFileHandle *handle = [NSFileHandle fileHandleForWritingToURL:fileURL error:&error];
|
||||
if (handle == nil) return [RACSignal error:error];
|
||||
|
||||
unsigned long long fileLength = [handle seekToEndOfFile];
|
||||
if (fileLength <= MAX_LENGTH) return [RACSignal empty];
|
||||
|
||||
[handle seekToFileOffset:fileLength - MAX_LENGTH];
|
||||
NSData *mostRecentData = [handle readDataToEndOfFile];
|
||||
[handle truncateFileAtOffset:0];
|
||||
[handle writeData:mostRecentData];
|
||||
|
||||
return [RACSignal empty];
|
||||
}];
|
||||
}
|
||||
|
||||
- (RACSignal *)truncateLogs {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItLauncher.shipItJobLabel];
|
||||
return [RACSignal zip:@[ [directoryManager shipItStdoutURL], [directoryManager shipItStderrURL] ]];
|
||||
}]
|
||||
reduceEach:^(NSURL *stdoutURL, NSURL *stderrURL) {
|
||||
return [RACSignal merge:@[ [self backwardTruncateFile:stdoutURL], [self backwardTruncateFile:stderrURL] ]];
|
||||
}];
|
||||
}
|
||||
|
||||
#pragma mark Installing Updates
|
||||
|
||||
- (RACSignal *)verifyAndPrepareUpdate:(SQRLUpdate *)update fromBundle:(NSBundle *)updateBundle {
|
||||
@@ -403,30 +581,14 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
|
||||
return [[[[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItLauncher.shipItJobLabel];
|
||||
RACSignal *stateLocation = directoryManager.shipItStateURL;
|
||||
return [[[[SQRLShipItState
|
||||
readUsingURL:stateLocation]
|
||||
catchTo:[RACSignal empty]]
|
||||
flattenMap:^(SQRLShipItState *existingState) {
|
||||
if (existingState.installerState != SQRLInstallerStateNothingToDo) {
|
||||
// If this happens, shit is crazy, because it implies that an
|
||||
// update is being installed over us right now.
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Installation in progress", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:NSLocalizedString(@"An update for %@ is already in progress.", nil), NSRunningApplication.currentApplication.bundleIdentifier],
|
||||
};
|
||||
NSRunningApplication *currentApplication = NSRunningApplication.currentApplication;
|
||||
NSBundle *appBundle = [NSBundle bundleWithURL:currentApplication.bundleURL];
|
||||
// Only use the update bundle's name if the user hasn't renamed the
|
||||
// app themselves.
|
||||
BOOL useUpdateBundleName = [appBundle.sqrl_executableName isEqual:currentApplication.bundleURL.lastPathComponent.stringByDeletingPathExtension];
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLErrorDomain code:SQRLUpdaterErrorPreparingUpdateJob userInfo:userInfo]];
|
||||
}
|
||||
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
then:^{
|
||||
SQRLShipItState *state = [[SQRLShipItState alloc] initWithTargetBundleURL:NSRunningApplication.currentApplication.bundleURL updateBundleURL:update.bundle.bundleURL bundleIdentifier:NSRunningApplication.currentApplication.bundleIdentifier codeSignature:self.signature];
|
||||
state.relaunchAfterInstallation = self.shouldRelaunch;
|
||||
return [state writeUsingURL:stateLocation];
|
||||
}];
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:update.bundle.bundleURL targetBundleURL:currentApplication.bundleURL bundleIdentifier:currentApplication.bundleIdentifier launchAfterInstallation:NO useUpdateBundleName:useUpdateBundleName];
|
||||
return [request writeUsingURL:self.shipItStateURL];
|
||||
}]
|
||||
then:^{
|
||||
return self.shipItLauncher;
|
||||
@@ -435,4 +597,26 @@ NSString * const SQRLUpdaterJSONObjectErrorKey = @"SQRLUpdaterJSONObjectErrorKey
|
||||
setNameWithFormat:@"%@ -prepareUpdateForInstallation: %@", self, update];
|
||||
}
|
||||
|
||||
- (RACSignal *)relaunchToInstallUpdate {
|
||||
return [[[[[[[[SQRLShipItRequest
|
||||
readUsingURL:self.shipItStateURL]
|
||||
map:^(SQRLShipItRequest *request) {
|
||||
return [[SQRLShipItRequest alloc] initWithUpdateBundleURL:request.updateBundleURL targetBundleURL:request.targetBundleURL bundleIdentifier:request.bundleIdentifier launchAfterInstallation:YES useUpdateBundleName:request.useUpdateBundleName];
|
||||
}]
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return [[request
|
||||
writeUsingURL:self.shipItStateURL]
|
||||
sqrl_addTransactionWithName:NSLocalizedString(@"Preparing to relaunch", nil) description:NSLocalizedString(@"%@ is preparing to relaunch to install an update. Interrupting the process could corrupt the application.", nil), NSRunningApplication.currentApplication.bundleIdentifier];
|
||||
}]
|
||||
deliverOn:RACScheduler.mainThreadScheduler]
|
||||
doCompleted:^{
|
||||
[NSApp terminate:self];
|
||||
}]
|
||||
// Never allow `completed` to escape this signal chain (in case
|
||||
// -terminate: is asynchronous or something crazy).
|
||||
concat:[RACSignal never]]
|
||||
replay]
|
||||
setNameWithFormat:@"%@ -relaunchToInstallUpdate", self];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -10,10 +10,17 @@
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
extern NSString * const SQRLZipArchiverErrorDomain;
|
||||
|
||||
// Associated with an NSNumber containing the code that a shell task exited
|
||||
// with.
|
||||
extern NSString * const SQRLZipArchiverExitCodeErrorKey;
|
||||
|
||||
// `SQRLZipArchiver` tried to invoke the shell and failed.
|
||||
//
|
||||
// Contains `SQRLZipArchiverExitStatusErrorKey` in the `userInfo` dictionary.
|
||||
extern const NSInteger SQRLZipArchiverShellTaskFailed;
|
||||
|
||||
// Uses `ditto` on the command line to zip and unzip archives.
|
||||
@interface SQRLZipArchiver : NSObject
|
||||
|
||||
|
||||
@@ -9,9 +9,10 @@
|
||||
#import "SQRLZipArchiver.h"
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import "Squirrel-Constants.h"
|
||||
|
||||
NSString * const SQRLZipArchiverErrorDomain = @"SQRLZipArchiverErrorDomain";
|
||||
NSString * const SQRLZipArchiverExitCodeErrorKey = @"SQRLZipArchiverExitCodeErrorKey";
|
||||
const NSInteger SQRLZipArchiverShellTaskFailed = 1;
|
||||
|
||||
@interface SQRLZipArchiver () {
|
||||
RACSubject *_taskTerminated;
|
||||
@@ -142,7 +143,7 @@ NSString * const SQRLZipArchiverExitCodeErrorKey = @"SQRLZipArchiverExitCodeErro
|
||||
errorString = [errorString stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
|
||||
if (errorString.length > 0) userInfo[NSLocalizedDescriptionKey] = errorString;
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLErrorDomain code:SQRLZipArchiverShellTaskFailed userInfo:userInfo]];
|
||||
return [RACSignal error:[NSError errorWithDomain:SQRLZipArchiverErrorDomain code:SQRLZipArchiverShellTaskFailed userInfo:userInfo]];
|
||||
}];
|
||||
}]
|
||||
take:1]
|
||||
|
||||
+115
-72
@@ -7,15 +7,19 @@
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
|
||||
#import "EXTScope.h"
|
||||
#import <ReactiveCocoa/RACCommand.h>
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
#import <ReactiveCocoa/RACScheduler.h>
|
||||
|
||||
#import "NSError+SQRLVerbosityExtensions.h"
|
||||
#import "RACSignal+SQRLTransactionExtensions.h"
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLInstaller.h"
|
||||
#import "SQRLShipItState.h"
|
||||
#import "SQRLInstaller+Private.h"
|
||||
#import "SQRLTerminationListener.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
|
||||
// The maximum number of times ShipIt should run the same installation state, in
|
||||
// an attempt to update.
|
||||
@@ -24,19 +28,120 @@
|
||||
// updating will abort.
|
||||
static const NSUInteger SQRLShipItMaximumInstallationAttempts = 3;
|
||||
|
||||
// The domain for errors generated here.
|
||||
static NSString * const SQRLShipItErrorDomain = @"SQRLShipItErrorDomain";
|
||||
|
||||
static NSUInteger installationAttempts(NSString *applicationIdentifier) {
|
||||
return CFPreferencesGetAppIntegerValue((__bridge CFStringRef)SQRLShipItInstallationAttemptsKey, (__bridge CFStringRef)applicationIdentifier, NULL);
|
||||
}
|
||||
|
||||
static BOOL setInstallationAttempts(NSString *applicationIdentifier, NSUInteger attempts) {
|
||||
CFPreferencesSetValue((__bridge CFStringRef)SQRLShipItInstallationAttemptsKey, (__bridge CFPropertyListRef)@(attempts), (__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
return CFPreferencesSynchronize((__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
}
|
||||
|
||||
static BOOL clearInstallationAttempts(NSString *applicationIdentifier) {
|
||||
CFPreferencesSetValue((__bridge CFStringRef)SQRLShipItInstallationAttemptsKey, NULL, (__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
return CFPreferencesSynchronize((__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
}
|
||||
|
||||
// Waits for all instances of the target application (as described in the
|
||||
// `state`) to exit, then sends completed.
|
||||
static RACSignal *waitForTerminationIfNecessary(SQRLShipItState *state) {
|
||||
// `request`) to exit, then sends completed.
|
||||
static RACSignal *waitForTerminationIfNecessary(SQRLShipItRequest *request) {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
if (state.bundleIdentifier == nil) return [RACSignal empty];
|
||||
if (request.bundleIdentifier == nil) return [RACSignal empty];
|
||||
|
||||
SQRLTerminationListener *listener = [[SQRLTerminationListener alloc] initWithURL:state.targetBundleURL bundleIdentifier:state.bundleIdentifier];
|
||||
SQRLTerminationListener *listener = [[SQRLTerminationListener alloc] initWithURL:request.targetBundleURL bundleIdentifier:request.bundleIdentifier];
|
||||
return [listener waitForTermination];
|
||||
}]
|
||||
setNameWithFormat:@"waitForTerminationIfNecessary"];
|
||||
}
|
||||
|
||||
static void installRequest(RACSignal *readRequestSignal, SQRLDirectoryManager *directoryManager) {
|
||||
NSString *applicationIdentifier = directoryManager.applicationIdentifier;
|
||||
|
||||
[[[[[readRequestSignal
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return waitForTerminationIfNecessary(request);
|
||||
}]
|
||||
ignoreValues]
|
||||
concat:readRequestSignal]
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
SQRLInstaller *installer = [[SQRLInstaller alloc] initWithApplicationIdentifier:applicationIdentifier];
|
||||
|
||||
NSUInteger attempt = installationAttempts(applicationIdentifier) + 1;
|
||||
setInstallationAttempts(applicationIdentifier, attempt);
|
||||
|
||||
RACSignal *action;
|
||||
if (attempt > SQRLShipItMaximumInstallationAttempts) {
|
||||
action = [[[[installer.abortInstallationCommand
|
||||
execute:request]
|
||||
initially:^{
|
||||
NSLog(@"Too many attempts to install, aborting update");
|
||||
}]
|
||||
catch:^(NSError *error) {
|
||||
NSLog(@"Error aborting installation: %@", error);
|
||||
|
||||
// Exit successfully so launchd doesn't restart us
|
||||
// again.
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
concat:[RACSignal return:request]];
|
||||
} else {
|
||||
action = [[[[installer.installUpdateCommand
|
||||
execute:request]
|
||||
initially:^{
|
||||
BOOL freshInstall = (attempt == 1);
|
||||
if (freshInstall) {
|
||||
NSLog(@"Beginning installation");
|
||||
} else {
|
||||
NSLog(@"Resuming installation attempt %i", (int)attempt);
|
||||
}
|
||||
}]
|
||||
doCompleted:^{
|
||||
NSLog(@"Installation completed successfully");
|
||||
}]
|
||||
sqrl_addTransactionWithName:NSLocalizedString(@"Updating", nil) description:NSLocalizedString(@"%@ is being updated, and interrupting the process could corrupt the application", nil), request.targetBundleURL.path];
|
||||
}
|
||||
|
||||
// Clear the installation attempts for a successful abort or
|
||||
// install.
|
||||
action = [action doCompleted:^{
|
||||
clearInstallationAttempts(applicationIdentifier);
|
||||
}];
|
||||
|
||||
if (request.launchAfterInstallation) {
|
||||
// Launch regardless of whether installation succeeds or fails.
|
||||
action = [[action
|
||||
deliverOn:RACScheduler.mainThreadScheduler]
|
||||
doNext:^(SQRLShipItRequest *finalRequest) {
|
||||
NSURL *bundleURL = finalRequest.targetBundleURL;
|
||||
if (bundleURL == nil) {
|
||||
NSLog(@"Missing target bundle URL, cannot launch application");
|
||||
return;
|
||||
}
|
||||
|
||||
NSError *error;
|
||||
if (![NSWorkspace.sharedWorkspace launchApplicationAtURL:bundleURL options:NSWorkspaceLaunchDefault configuration:@{} error:&error]) {
|
||||
NSLog(@"Could not launch application at %@: %@", bundleURL, error);
|
||||
return;
|
||||
}
|
||||
|
||||
NSLog(@"Application launched at %@", bundleURL);
|
||||
}];
|
||||
}
|
||||
|
||||
return action;
|
||||
}]
|
||||
subscribeError:^(NSError *error) {
|
||||
NSLog(@"Installation error: %@", error);
|
||||
exit(EXIT_FAILURE);
|
||||
} completed:^{
|
||||
exit(EXIT_SUCCESS);
|
||||
}];
|
||||
}
|
||||
|
||||
int main(int argc, const char * argv[]) {
|
||||
@autoreleasepool {
|
||||
atexit_b(^{
|
||||
@@ -48,75 +153,13 @@ int main(int argc, const char * argv[]) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
const char *jobLabel = argv[1];
|
||||
char const *jobLabel = argv[1];
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:@(jobLabel)];
|
||||
RACSignal *stateLocation = directoryManager.shipItStateURL;
|
||||
|
||||
[[[[[[SQRLShipItState
|
||||
readUsingURL:stateLocation]
|
||||
flattenMap:^(SQRLShipItState *state) {
|
||||
return waitForTerminationIfNecessary(state);
|
||||
}]
|
||||
then:^{
|
||||
// Read the latest state, in case it was modified by the
|
||||
// controlling application in the meantime.
|
||||
return [SQRLShipItState readUsingURL:stateLocation];
|
||||
}]
|
||||
catch:^(NSError *error) {
|
||||
NSLog(@"Error reading saved installer state: %@", error);
|
||||
|
||||
// Exit successfully so launchd doesn't restart us again.
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
flattenMap:^(SQRLShipItState *state) {
|
||||
BOOL freshInstall = (state.installerState == SQRLInstallerStateNothingToDo);
|
||||
SQRLInstaller *installer = [[SQRLInstaller alloc] initWithDirectoryManager:directoryManager];
|
||||
|
||||
NSUInteger attempt = (freshInstall ? 1 : state.installationStateAttempt + 1);
|
||||
if (attempt > SQRLShipItMaximumInstallationAttempts) {
|
||||
return [[[installer.abortInstallationCommand
|
||||
execute:state]
|
||||
initially:^{
|
||||
NSLog(@"Too many attempts to install from state %i, aborting update", (int)state.installerState);
|
||||
}]
|
||||
catch:^(NSError *error) {
|
||||
NSLog(@"Error aborting installation: %@", error);
|
||||
|
||||
// Exit successfully so launchd doesn't restart us again.
|
||||
return [RACSignal empty];
|
||||
}];
|
||||
} else {
|
||||
return [[[[[state
|
||||
writeUsingURL:stateLocation]
|
||||
initially:^{
|
||||
if (freshInstall) {
|
||||
NSLog(@"Beginning installation");
|
||||
state.installerState = SQRLInstallerStateClearingQuarantine;
|
||||
} else {
|
||||
NSLog(@"Resuming installation from state %i", (int)state.installerState);
|
||||
}
|
||||
|
||||
state.installationStateAttempt = attempt;
|
||||
}]
|
||||
then:^{
|
||||
return [installer.installUpdateCommand execute:state];
|
||||
}]
|
||||
doCompleted:^{
|
||||
NSLog(@"Installation completed successfully");
|
||||
}]
|
||||
sqrl_addTransactionWithName:NSLocalizedString(@"Updating", nil) description:NSLocalizedString(@"%@ is being updated, and interrupting the process could corrupt the application", nil), state.targetBundleURL.path];
|
||||
}
|
||||
}]
|
||||
subscribeError:^(NSError *error) {
|
||||
NSLog(@"Installation error: %@", error);
|
||||
exit(EXIT_FAILURE);
|
||||
} completed:^{
|
||||
exit(EXIT_SUCCESS);
|
||||
}];
|
||||
installRequest([SQRLShipItRequest readUsingURL:directoryManager.shipItStateURL], directoryManager);
|
||||
|
||||
dispatch_main();
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
//
|
||||
// Squirrel-Constants.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 30/10/2013.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
// Error domain for errors originating in Squirrel.
|
||||
extern NSString * const SQRLErrorDomain;
|
||||
|
||||
// Error codes for errors originating in Squirrel.
|
||||
//
|
||||
// SQRLCodeSignatureErrorDidNotPass - The bundle did not pass codesign
|
||||
// verification.
|
||||
//
|
||||
// SQRLCodeSignatureErrorCouldNotCreateStaticCode - A static code object could
|
||||
// not be created for the target bundle or running code.
|
||||
//
|
||||
// SQRLShipItStateErrorMissingRequiredProperty - A required property was `nil`
|
||||
// upon initialization. Includes `SQRLShipItStatePropertyErrorKey` in the
|
||||
// error's `userInfo` dictionary.
|
||||
//
|
||||
// SQRLShipItStateErrorUnarchiving - The saved state on disk could not be
|
||||
// unarchived, possibly because it's invalid.
|
||||
//
|
||||
// SQRLShipItStateErrorArchiving - The state object could not be archived.
|
||||
//
|
||||
// SQRLUpdaterErrorMissingUpdateBundle - The downloaded update does not contain
|
||||
// an app bundle, or it was deleted on disk before we could get to it.
|
||||
//
|
||||
// SQRLUpdaterErrorPreparingUpdateJob - An error occurred in the out-of-process
|
||||
// updater while it was setting up.
|
||||
//
|
||||
// SQRLUpdaterErrorRetrievingCodeSigningRequirement - The code signing
|
||||
// requirement for the running application could not be retrieved.
|
||||
//
|
||||
// SQRLUpdaterErrorInvalidServerResponse - The server sent a response that we
|
||||
// didn't understand. Includes `SQRLUpdaterServerDataErrorKey` in the error's
|
||||
// `userInfo` dictionary.
|
||||
//
|
||||
// SQRLUpdaterErrorInvalidJSON - The server sent update JSON that we didn't
|
||||
// understand. Includes `SQRLUpdaterJSONObjectErrorKey` in the error's
|
||||
// `userInfo` dictionary.
|
||||
//
|
||||
// SQRLZipArchiverShellTaskFailed - `SQRLZipArchiver` tried to invoke the shell
|
||||
// and failed. Includes `SQRLZipArchiverExitStatusErrorKey` in the error's
|
||||
// `userInfo` dictionary.
|
||||
//
|
||||
// SQRLShipItLauncherErrorCouldNotStartService - The ShipIt service could not be
|
||||
// started.
|
||||
typedef enum : NSInteger {
|
||||
SQRLCodeSignatureErrorDidNotPass = -1,
|
||||
SQRLCodeSignatureErrorCouldNotCreateStaticCode = -2,
|
||||
|
||||
SQRLShipItStateErrorMissingRequiredProperty = -100,
|
||||
SQRLShipItStateErrorUnarchiving = -101,
|
||||
SQRLShipItStateErrorArchiving = -102,
|
||||
|
||||
SQRLUpdaterErrorMissingUpdateBundle = -200,
|
||||
SQRLUpdaterErrorPreparingUpdateJob = -201,
|
||||
SQRLUpdaterErrorRetrievingCodeSigningRequirement = -202,
|
||||
SQRLUpdaterErrorInvalidServerResponse = -203,
|
||||
SQRLUpdaterErrorInvalidJSON = -204,
|
||||
|
||||
SQRLZipArchiverShellTaskFailed = -300,
|
||||
|
||||
SQRLShipItLauncherErrorCouldNotStartService = -400,
|
||||
} SQRLErrorCode;
|
||||
@@ -1,11 +0,0 @@
|
||||
//
|
||||
// Squirrel-Constants.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 30/10/2013.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "Squirrel-Constants.h"
|
||||
|
||||
NSString * const SQRLErrorDomain = @"SQRLErrorDomain";
|
||||
@@ -9,7 +9,7 @@
|
||||
<key>CFBundleIconFile</key>
|
||||
<string></string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.github.${PRODUCT_NAME:rfc1034identifier}</string>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
//
|
||||
// Prefix header for all source files of the 'Squirrel' target in the 'Squirrel' project
|
||||
//
|
||||
|
||||
#ifdef __OBJC__
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <SystemConfiguration/SystemConfiguration.h>
|
||||
#endif
|
||||
@@ -6,6 +6,14 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
//! Project version number for Squirrel.
|
||||
FOUNDATION_EXPORT double SquirrelVersionNumber;
|
||||
|
||||
//! Project version string for Squirrel.
|
||||
FOUNDATION_EXPORT const unsigned char SquirrelVersionString[];
|
||||
|
||||
#import <Squirrel/NSBundle+SQRLVersionExtensions.h>
|
||||
#import <Squirrel/NSProcessInfo+SQRLVersionExtensions.h>
|
||||
#import <Squirrel/SQRLDownloadedUpdate.h>
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
/* Localized versions of Info.plist keys */
|
||||
|
||||
@@ -6,30 +6,35 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
SpecBegin(NSProcessInfoExtensions)
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
QuickSpecBegin(NSProcessInfoExtensions)
|
||||
|
||||
describe(@"-sqrl_operatingSystemShortVersionString", ^{
|
||||
__block NSString *versionString;
|
||||
|
||||
beforeEach(^{
|
||||
versionString = NSProcessInfo.processInfo.sqrl_operatingSystemShortVersionString;
|
||||
expect(versionString).notTo.beNil();
|
||||
expect(versionString).notTo(beNil());
|
||||
});
|
||||
|
||||
it(@"should follow major.minor.patch format", ^{
|
||||
NSError *error = nil;
|
||||
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]+(\\.[0-9]+)*$" options:0 error:&error];
|
||||
expect(regex).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
expect(regex).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
|
||||
NSRange fullRange = NSMakeRange(0, versionString.length);
|
||||
NSRange matchRange = [regex rangeOfFirstMatchInString:versionString options:0 range:fullRange];
|
||||
expect(NSEqualRanges(matchRange, fullRange)).to.beTruthy();
|
||||
expect(@(NSEqualRanges(matchRange, fullRange))).to(beTruthy());
|
||||
});
|
||||
|
||||
it(@"should be numerically comparable", ^{
|
||||
expect([@"10.6.9" compare:versionString options:NSNumericSearch]).to.equal(NSOrderedAscending);
|
||||
expect(@([@"10.6.9" compare:versionString options:NSNumericSearch])).to(equal(@(NSOrderedAscending)));
|
||||
});
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
QuickSpecEnd
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
//
|
||||
// SQRLTestCase.h
|
||||
// QuickSpec+SQRLFixtures.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-08-06.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
/// See https://github.com/Squirrel/Squirrel.Mac/pull/154#issuecomment-151287744
|
||||
#define SKIP_IF_RUNNING_ON_TRAVIS if (self.runningOnTravis) return;
|
||||
|
||||
// The short version string for the `testApplicationBundle`.
|
||||
extern NSString * const SQRLTestApplicationOriginalShortVersionString;
|
||||
|
||||
@@ -16,10 +24,15 @@ extern NSString * const SQRLTestApplicationUpdatedShortVersionString;
|
||||
// The Info.plist key associated with a bundle's short version string.
|
||||
extern NSString * const SQRLBundleShortVersionStringKey;
|
||||
|
||||
/// The longer timeout we should use for things that take a long time. This is
|
||||
/// especially needed on slower machines (e.g., Travis CI).
|
||||
extern const NSTimeInterval SQRLLongTimeout;
|
||||
|
||||
@class SQRLCodeSignature;
|
||||
@class SQRLDirectoryManager;
|
||||
@class SQRLShipItRequest;
|
||||
|
||||
@interface SQRLTestCase : SPTSenTestCase
|
||||
@interface QuickSpec (SQRLFixtures)
|
||||
|
||||
// A URL to a temporary directory tests can use.
|
||||
//
|
||||
@@ -45,13 +58,12 @@ extern NSString * const SQRLBundleShortVersionStringKey;
|
||||
// A code signature with requirements from TestApplication.app.
|
||||
@property (nonatomic, strong, readonly) SQRLCodeSignature *testApplicationSignature;
|
||||
|
||||
// A serialized `SecRequirementRef` representing the requirements from
|
||||
// TestApplication.app.
|
||||
@property (nonatomic, copy, readonly) NSData *testApplicationCodeSigningRequirementData;
|
||||
|
||||
// A directory manager for finding URLs that apply to ShipIt.
|
||||
@property (nonatomic, strong, readonly) SQRLDirectoryManager *shipItDirectoryManager;
|
||||
|
||||
/// Are the tests currently being run on Travis?
|
||||
@property (nonatomic, readonly, assign, getter = isRunningOnTravis) BOOL runningOnTravis;
|
||||
|
||||
// Launches a new copy of TestApplication.app from the `testApplicationBundle`.
|
||||
//
|
||||
// Invoking this method multiple times will result in multiple running instances
|
||||
@@ -74,8 +86,8 @@ extern NSString * const SQRLBundleShortVersionStringKey;
|
||||
// deleted at the end of the example.
|
||||
- (NSURL *)createTestApplicationUpdate;
|
||||
|
||||
// Submits ShipIt's launchd job to start it up.
|
||||
- (void)launchShipIt;
|
||||
// Runs the installer in process or submits ShipIt's launchd job to start it up.
|
||||
- (void)installWithRequest:(SQRLShipItRequest *)request remote:(BOOL)remote;
|
||||
|
||||
// Creates a disk image, then mounts it.
|
||||
//
|
||||
@@ -88,4 +100,11 @@ extern NSString * const SQRLBundleShortVersionStringKey;
|
||||
// automatically be unmounted and deleted at the end of the example.
|
||||
- (NSURL *)createAndMountDiskImageNamed:(NSString *)name fromDirectory:(NSURL *)directoryURL;
|
||||
|
||||
// Add a block to cleanup after each example has run
|
||||
//
|
||||
// Blocks are run in reverse order, i.e. LIFO
|
||||
//
|
||||
// block - The block to invoke after the current example has finished
|
||||
- (void)addCleanupBlock:(dispatch_block_t)block;
|
||||
|
||||
@end
|
||||
@@ -1,16 +1,20 @@
|
||||
//
|
||||
// SQRLTestCase.m
|
||||
// QuickSpec+SQRLFixtures.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-08-06.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLTestCase.h"
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLInstaller.h"
|
||||
#import "SQRLShipItLauncher.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
#import <ServiceManagement/ServiceManagement.h>
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
||||
@@ -19,6 +23,8 @@ NSString * const SQRLTestApplicationOriginalShortVersionString = @"1.0";
|
||||
NSString * const SQRLTestApplicationUpdatedShortVersionString = @"2.1";
|
||||
NSString * const SQRLBundleShortVersionStringKey = @"CFBundleShortVersionString";
|
||||
|
||||
const NSTimeInterval SQRLLongTimeout = 20;
|
||||
|
||||
static void SQRLKillAllTestApplications(void) {
|
||||
// Forcibly kill all copies of the TestApplication that may be running.
|
||||
NSArray *apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.github.Squirrel.TestApplication"];
|
||||
@@ -39,36 +45,25 @@ static void SQRLSignalHandler(int sig) {
|
||||
abort();
|
||||
}
|
||||
|
||||
@interface SQRLTestCase ()
|
||||
static NSBundle *SQRLTestBundle(void) {
|
||||
return [NSBundle bundleWithIdentifier:@"com.github.SquirrelTests"];
|
||||
}
|
||||
|
||||
// An array of dispatch_block_t values, for performing cleanup after the current
|
||||
// example finishes.
|
||||
//
|
||||
// This array will be emptied between each example.
|
||||
@property (nonatomic, strong, readonly) NSMutableArray *exampleCleanupBlocks;
|
||||
static NSMutableArray *cleanupBlocks = nil;
|
||||
|
||||
// The URL to the temporary directory which contains `temporaryDirectoryURL` and
|
||||
// all copied test data.
|
||||
@property (nonatomic, copy, readonly) NSURL *baseTemporaryDirectoryURL;
|
||||
static NSURL *baseTemporaryDirectoryURL = nil;
|
||||
|
||||
@end
|
||||
QuickConfigurationBegin(Fixtures)
|
||||
|
||||
@implementation SQRLTestCase
|
||||
|
||||
#pragma mark Properties
|
||||
|
||||
@synthesize baseTemporaryDirectoryURL = _baseTemporaryDirectoryURL;
|
||||
|
||||
#pragma mark Lifecycle
|
||||
|
||||
+ (void)load {
|
||||
+ (void)configure:(Configuration *)configuration {
|
||||
NSURL *appSupportURL = [NSFileManager.defaultManager URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:NULL];
|
||||
NSAssert(appSupportURL != nil, @"Could not find Application Support folder");
|
||||
|
||||
NSArray *folders = @[
|
||||
@"com.github.Squirrel.TestApplication.ShipIt",
|
||||
@"otest.ShipIt",
|
||||
@"otest-x86_64.ShipIt",
|
||||
@"com.github.Squirrel.SquirrelTests.ShipIt",
|
||||
];
|
||||
|
||||
RACSequence *URLs = [folders.rac_sequence flattenMap:^(NSString *folder) {
|
||||
@@ -79,76 +74,69 @@ static void SQRLSignalHandler(int sig) {
|
||||
].rac_sequence;
|
||||
}];
|
||||
|
||||
for (NSURL *URL in URLs) {
|
||||
[[NSData data] writeToURL:URL atomically:YES];
|
||||
}
|
||||
[configuration beforeSuite:^{
|
||||
signal(SIGILL, &SQRLSignalHandler);
|
||||
NSSetUncaughtExceptionHandler(&SQRLUncaughtExceptionHandler);
|
||||
|
||||
NSArray *args = [[[URLs
|
||||
map:^(NSURL *URL) {
|
||||
return URL.path;
|
||||
}]
|
||||
startWith:@"-f"]
|
||||
array];
|
||||
cleanupBlocks = [NSMutableArray array];
|
||||
|
||||
NSTask *readShipIt = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/tail" arguments:args];
|
||||
NSAssert([readShipIt isRunning], @"Could not start task %@ with arguments: %@", readShipIt, args);
|
||||
for (NSURL *URL in URLs) {
|
||||
[NSFileManager.defaultManager createDirectoryAtURL:URL.URLByDeletingLastPathComponent withIntermediateDirectories:YES attributes:nil error:NULL];
|
||||
if (![[NSData data] writeToURL:URL atomically:YES]) {
|
||||
NSLog(@"Could not touch log file at %@", URL);
|
||||
}
|
||||
}
|
||||
}];
|
||||
|
||||
atexit_b(^{
|
||||
[readShipIt terminate];
|
||||
});
|
||||
// We want to run any enqueued cleanup blocks after _and before_ each spec,
|
||||
// in case beforeSuites (for example) use the fixtures.
|
||||
void (^runCleanupBlocks)(void) = ^{
|
||||
// Enumerate backwards, so later resources are cleaned up first.
|
||||
for (dispatch_block_t block in cleanupBlocks.reverseObjectEnumerator) {
|
||||
block();
|
||||
}
|
||||
|
||||
[cleanupBlocks removeAllObjects];
|
||||
};
|
||||
|
||||
[configuration beforeEach:^{
|
||||
runCleanupBlocks();
|
||||
}];
|
||||
|
||||
[configuration afterEach:^{
|
||||
runCleanupBlocks();
|
||||
SQRLKillAllTestApplications();
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)setUp {
|
||||
[super setUp];
|
||||
QuickConfigurationEnd
|
||||
|
||||
signal(SIGILL, &SQRLSignalHandler);
|
||||
NSSetUncaughtExceptionHandler(&SQRLUncaughtExceptionHandler);
|
||||
@implementation QuickSpec (SQRLFixtures)
|
||||
|
||||
Expecta.asynchronousTestTimeout = 3;
|
||||
}
|
||||
|
||||
- (void)SPT_setUp {
|
||||
_exampleCleanupBlocks = [[NSMutableArray alloc] init];
|
||||
}
|
||||
|
||||
- (void)SPT_tearDown {
|
||||
NSArray *cleanupBlocks = [self.exampleCleanupBlocks copy];
|
||||
_exampleCleanupBlocks = nil;
|
||||
|
||||
// Enumerate backwards, so later resources are cleaned up first.
|
||||
for (dispatch_block_t block in cleanupBlocks.reverseObjectEnumerator) {
|
||||
block();
|
||||
}
|
||||
}
|
||||
|
||||
- (void)tearDown {
|
||||
[super tearDown];
|
||||
|
||||
SQRLKillAllTestApplications();
|
||||
}
|
||||
#pragma mark Lifecycle
|
||||
|
||||
- (void)addCleanupBlock:(dispatch_block_t)block {
|
||||
[self.exampleCleanupBlocks addObject:[block copy]];
|
||||
[cleanupBlocks addObject:[block copy]];
|
||||
}
|
||||
|
||||
#pragma mark Temporary Directory
|
||||
|
||||
- (NSURL *)baseTemporaryDirectoryURL {
|
||||
if (_baseTemporaryDirectoryURL == nil) {
|
||||
if (baseTemporaryDirectoryURL == nil) {
|
||||
NSURL *globalTemporaryDirectory = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
|
||||
_baseTemporaryDirectoryURL = [[globalTemporaryDirectory URLByAppendingPathComponent:@"com.github.SquirrelTests"] URLByAppendingPathComponent:[NSProcessInfo.processInfo globallyUniqueString]];
|
||||
|
||||
baseTemporaryDirectoryURL = [[globalTemporaryDirectory URLByAppendingPathComponent:@"com.github.SquirrelTests"] URLByAppendingPathComponent:[NSProcessInfo.processInfo globallyUniqueString]];
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [NSFileManager.defaultManager createDirectoryAtURL:_baseTemporaryDirectoryURL withIntermediateDirectories:YES attributes:nil error:&error];
|
||||
STAssertTrue(success, @"Couldn't create temporary directory at %@: %@", _baseTemporaryDirectoryURL, error);
|
||||
BOOL success = [NSFileManager.defaultManager createDirectoryAtURL:baseTemporaryDirectoryURL withIntermediateDirectories:YES attributes:nil error:&error];
|
||||
XCTAssertTrue(success, @"Couldn't create temporary directory at %@: %@", baseTemporaryDirectoryURL, error);
|
||||
|
||||
[self addCleanupBlock:^{
|
||||
[NSFileManager.defaultManager removeItemAtURL:_baseTemporaryDirectoryURL error:NULL];
|
||||
_baseTemporaryDirectoryURL = nil;
|
||||
[NSFileManager.defaultManager removeItemAtURL:baseTemporaryDirectoryURL error:NULL];
|
||||
baseTemporaryDirectoryURL = nil;
|
||||
}];
|
||||
}
|
||||
|
||||
return _baseTemporaryDirectoryURL;
|
||||
return baseTemporaryDirectoryURL;
|
||||
}
|
||||
|
||||
- (NSURL *)temporaryDirectoryURL {
|
||||
@@ -156,7 +144,7 @@ static void SQRLSignalHandler(int sig) {
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [NSFileManager.defaultManager createDirectoryAtURL:temporaryDirectoryURL withIntermediateDirectories:YES attributes:nil error:&error];
|
||||
STAssertTrue(success, @"Couldn't create temporary directory at %@: %@", temporaryDirectoryURL, error);
|
||||
XCTAssertTrue(success, @"Couldn't create temporary directory at %@: %@", temporaryDirectoryURL, error);
|
||||
|
||||
return temporaryDirectoryURL;
|
||||
}
|
||||
@@ -166,22 +154,15 @@ static void SQRLSignalHandler(int sig) {
|
||||
- (NSURL *)testApplicationURL {
|
||||
NSURL *fixtureURL = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"TestApplication.app" isDirectory:YES];
|
||||
if (![NSFileManager.defaultManager fileExistsAtPath:fixtureURL.path]) {
|
||||
NSURL *bundleURL = [[NSBundle bundleForClass:self.class] URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
STAssertNotNil(bundleURL, @"Couldn't find TestApplication.app in test bundle");
|
||||
NSURL *bundleURL = [SQRLTestBundle() URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
XCTAssertNotNil(bundleURL, @"Couldn't find TestApplication.app in test bundle");
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [NSFileManager.defaultManager copyItemAtURL:bundleURL toURL:fixtureURL error:&error];
|
||||
STAssertTrue(success, @"Couldn't copy %@ to %@: %@", bundleURL, fixtureURL, error);
|
||||
XCTAssertTrue(success, @"Couldn't copy %@ to %@: %@", bundleURL, fixtureURL, error);
|
||||
|
||||
NSURL *testAppLog = [fixtureURL.URLByDeletingLastPathComponent URLByAppendingPathComponent:@"TestApplication.log"];
|
||||
[[NSData data] writeToURL:testAppLog atomically:YES];
|
||||
|
||||
NSTask *readTestApp = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/tail" arguments:@[ @"-f", testAppLog.path ]];
|
||||
STAssertTrue([readTestApp isRunning], @"Could not start task %@ to read %@", readTestApp, testAppLog);
|
||||
|
||||
[self addCleanupBlock:^{
|
||||
[readTestApp terminate];
|
||||
}];
|
||||
}
|
||||
|
||||
return fixtureURL;
|
||||
@@ -190,8 +171,8 @@ static void SQRLSignalHandler(int sig) {
|
||||
- (NSBundle *)testApplicationBundle {
|
||||
NSURL *fixtureURL = self.testApplicationURL;
|
||||
NSBundle *bundle = [NSBundle bundleWithURL:fixtureURL];
|
||||
STAssertNotNil(bundle, @"Couldn't open bundle at %@", fixtureURL);
|
||||
|
||||
XCTAssertNotNil(bundle, @"Couldn't open bundle at %@", fixtureURL);
|
||||
|
||||
return bundle;
|
||||
}
|
||||
|
||||
@@ -210,7 +191,7 @@ static void SQRLSignalHandler(int sig) {
|
||||
|
||||
NSError *error = nil;
|
||||
NSRunningApplication *app = [NSWorkspace.sharedWorkspace launchApplicationAtURL:self.testApplicationURL options:NSWorkspaceLaunchWithoutAddingToRecents | NSWorkspaceLaunchWithoutActivation | NSWorkspaceLaunchNewInstance | NSWorkspaceLaunchAndHide configuration:configuration error:&error];
|
||||
STAssertNotNil(app, @"Could not launch app at %@: %@", self.testApplicationURL, error);
|
||||
XCTAssertNotNil(app, @"Could not launch app at %@: %@", self.testApplicationURL, error);
|
||||
|
||||
[self addCleanupBlock:^{
|
||||
if (!app.terminated) {
|
||||
@@ -230,12 +211,12 @@ static void SQRLSignalHandler(int sig) {
|
||||
}
|
||||
|
||||
- (NSURL *)createTestApplicationUpdate {
|
||||
NSURL *originalURL = [[NSBundle bundleForClass:self.class] URLForResource:@"TestApplication 2.1" withExtension:@"app"];
|
||||
STAssertNotNil(originalURL, @"Couldn't find TestApplication update in test bundle");
|
||||
NSURL *originalURL = [SQRLTestBundle() URLForResource:@"TestApplication 2.1" withExtension:@"app"];
|
||||
XCTAssertNotNil(originalURL, @"Couldn't find TestApplication update in test bundle");
|
||||
|
||||
NSError *error = nil;
|
||||
NSURL *updateParentURL = [NSFileManager.defaultManager URLForDirectory:NSItemReplacementDirectory inDomain:NSUserDomainMask appropriateForURL:self.baseTemporaryDirectoryURL create:YES error:&error];
|
||||
STAssertNotNil(updateParentURL, @"Could not create temporary directory for updating: %@", error);
|
||||
XCTAssertNotNil(updateParentURL, @"Could not create temporary directory for updating: %@", error);
|
||||
|
||||
[self addCleanupBlock:^{
|
||||
[NSFileManager.defaultManager removeItemAtURL:updateParentURL error:NULL];
|
||||
@@ -243,18 +224,18 @@ static void SQRLSignalHandler(int sig) {
|
||||
|
||||
NSURL *updateURL = [updateParentURL URLByAppendingPathComponent:originalURL.lastPathComponent isDirectory:YES];
|
||||
BOOL success = [NSFileManager.defaultManager copyItemAtURL:originalURL toURL:updateURL error:&error];
|
||||
STAssertTrue(success, @"Couldn't copy %@ to %@: %@", originalURL, updateURL, error);
|
||||
XCTAssertTrue(success, @"Couldn't copy %@ to %@: %@", originalURL, updateURL, error);
|
||||
|
||||
return updateURL;
|
||||
}
|
||||
|
||||
- (id)performWithTestApplicationRequirement:(id (^)(SecRequirementRef requirement))block {
|
||||
NSURL *bundleURL = [[NSBundle bundleForClass:self.class] URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
STAssertNotNil(bundleURL, @"Couldn't find TestApplication.app in test bundle");
|
||||
NSURL *bundleURL = [SQRLTestBundle() URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
XCTAssertNotNil(bundleURL, @"Couldn't find TestApplication.app in test bundle");
|
||||
|
||||
SecStaticCodeRef staticCode = NULL;
|
||||
OSStatus status = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundleURL, kSecCSDefaultFlags, &staticCode);
|
||||
STAssertTrue(status == noErr, @"Error creating static code object for %@", bundleURL);
|
||||
XCTAssertTrue(status == noErr, @"Error creating static code object for %@", bundleURL);
|
||||
|
||||
@onExit {
|
||||
if (staticCode != NULL) CFRelease(staticCode);
|
||||
@@ -262,7 +243,7 @@ static void SQRLSignalHandler(int sig) {
|
||||
|
||||
SecRequirementRef requirement = NULL;
|
||||
status = SecCodeCopyDesignatedRequirement(staticCode, kSecCSDefaultFlags, &requirement);
|
||||
STAssertTrue(status == noErr, @"Error getting designated requirement of %@", staticCode);
|
||||
XCTAssertTrue(status == noErr, @"Error getting designated requirement of %@", staticCode);
|
||||
|
||||
@onExit {
|
||||
if (requirement != NULL) CFRelease(requirement);
|
||||
@@ -272,52 +253,57 @@ static void SQRLSignalHandler(int sig) {
|
||||
}
|
||||
|
||||
- (SQRLCodeSignature *)testApplicationSignature {
|
||||
return [self performWithTestApplicationRequirement:^(SecRequirementRef requirement) {
|
||||
return [[SQRLCodeSignature alloc] initWithRequirement:requirement];
|
||||
}];
|
||||
}
|
||||
NSURL *bundleURL = [SQRLTestBundle() URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
XCTAssertNotNil(bundleURL, @"Couldn't find TestApplication.app in test bundle");
|
||||
|
||||
- (NSData *)testApplicationCodeSigningRequirementData {
|
||||
return [self performWithTestApplicationRequirement:^(SecRequirementRef requirement) {
|
||||
CFDataRef data = NULL;
|
||||
OSStatus status = SecRequirementCopyData(requirement, kSecCSDefaultFlags, &data);
|
||||
STAssertTrue(status == noErr, @"Error copying data for requirement %@", requirement);
|
||||
NSError *error = nil;
|
||||
SQRLCodeSignature *signature = [SQRLCodeSignature signatureWithBundle:bundleURL error:&error];
|
||||
XCTAssertNotNil(signature, @"Error getting signature for bundle at %@: %@", bundleURL, error);
|
||||
|
||||
return CFBridgingRelease(data);
|
||||
}];
|
||||
return signature;
|
||||
}
|
||||
|
||||
- (SQRLDirectoryManager *)shipItDirectoryManager {
|
||||
NSString *identifier = SQRLShipItLauncher.shipItJobLabel;
|
||||
SQRLDirectoryManager *manager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:identifier];
|
||||
STAssertNotNil(manager, @"Could not create directory manager for %@", identifier);
|
||||
XCTAssertNotNil(manager, @"Could not create directory manager for %@", identifier);
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
- (void)launchShipIt {
|
||||
NSError *error = nil;
|
||||
STAssertTrue([[SQRLShipItLauncher launchPrivileged:NO] waitUntilCompleted:&error], @"Could not launch ShipIt: %@", error);
|
||||
- (void)installWithRequest:(SQRLShipItRequest *)request remote:(BOOL)remote {
|
||||
if (remote) {
|
||||
expect(@([[request writeUsingURL:self.shipItDirectoryManager.shipItStateURL] waitUntilCompleted:NULL])).to(beTruthy());
|
||||
|
||||
[self addCleanupBlock:^{
|
||||
// Remove ShipIt's launchd job so it doesn't relaunch itself.
|
||||
CFErrorRef removeError = NULL;
|
||||
if (!SMJobRemove(kSMDomainUserLaunchd, (__bridge CFStringRef)SQRLShipItLauncher.shipItJobLabel, NULL, true, &removeError)) {
|
||||
NSLog(@"Could not remove ShipIt job after tests: %@", removeError);
|
||||
if (removeError != NULL) CFRelease(removeError);
|
||||
}
|
||||
__block NSError *error = nil;
|
||||
expect(@([[SQRLShipItLauncher launchPrivileged:NO] waitUntilCompleted:&error])).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
NSError *lookupError = nil;
|
||||
NSURL *stateURL = [[self.shipItDirectoryManager shipItStateURL] firstOrDefault:nil success:NULL error:&lookupError];
|
||||
STAssertNotNil(stateURL, @"Could not find state URL from %@: %@", self.shipItDirectoryManager, lookupError);
|
||||
|
||||
[NSFileManager.defaultManager removeItemAtURL:stateURL error:NULL];
|
||||
}];
|
||||
[self addCleanupBlock:^{
|
||||
// Remove ShipIt's launchd job so it doesn't relaunch itself.
|
||||
SMJobRemove(kSMDomainUserLaunchd, (__bridge CFStringRef)SQRLShipItLauncher.shipItJobLabel, NULL, true, NULL);
|
||||
|
||||
NSError *lookupError;
|
||||
NSURL *stateURL = [[self.shipItDirectoryManager shipItStateURL] firstOrDefault:nil success:NULL error:&lookupError];
|
||||
expect(stateURL).notTo(beNil());
|
||||
expect(lookupError).to(beNil());
|
||||
|
||||
[NSFileManager.defaultManager removeItemAtURL:stateURL error:NULL];
|
||||
}];
|
||||
} else {
|
||||
SQRLInstaller *installer = [[SQRLInstaller alloc] initWithApplicationIdentifier:self.shipItDirectoryManager.applicationIdentifier];
|
||||
expect(installer).notTo(beNil());
|
||||
|
||||
NSError *installedError = nil;
|
||||
BOOL installed = [[installer.installUpdateCommand execute:request] asynchronouslyWaitUntilCompleted:&installedError];
|
||||
expect(@(installed)).to(beTruthy());
|
||||
expect(installedError).to(beNil());
|
||||
}
|
||||
}
|
||||
|
||||
- (NSURL *)createAndMountDiskImageNamed:(NSString *)name fromDirectory:(NSURL *)directoryURL {
|
||||
NSURL *destinationURL = [self.baseTemporaryDirectoryURL URLByAppendingPathComponent:name];
|
||||
STAssertNotNil(destinationURL, @"Could not create disk image URL for %@", directoryURL);
|
||||
XCTAssertNotNil(destinationURL, @"Could not create disk image URL for %@", directoryURL);
|
||||
|
||||
NSString *createInvocation;
|
||||
if (directoryURL == nil) {
|
||||
@@ -326,20 +312,24 @@ static void SQRLSignalHandler(int sig) {
|
||||
createInvocation = [NSString stringWithFormat:@"hdiutil create '%@' -fs 'HFS+' -volname '%@' -format UDSP -size 10m -srcfolder '%@' -quiet", destinationURL.path, name, directoryURL.path];
|
||||
}
|
||||
|
||||
expect(system(createInvocation.UTF8String)).to.equal(0);
|
||||
expect(@(system(createInvocation.UTF8String))).to(equal(@0));
|
||||
|
||||
NSString *mountInvocation = [NSString stringWithFormat:@"hdiutil attach '%@.sparseimage' -noverify -noautofsck -readwrite -quiet", destinationURL.path];
|
||||
expect(system(mountInvocation.UTF8String)).to.equal(0);
|
||||
expect(@(system(mountInvocation.UTF8String))).to(equal(@0));
|
||||
|
||||
NSString *path = [NSString stringWithFormat:@"/Volumes/%@", name];
|
||||
[self addCleanupBlock:^{
|
||||
NSString *detachInvocation = [NSString stringWithFormat:@"hdiutil detach '%@' -force -quiet", path];
|
||||
expect(system(detachInvocation.UTF8String)).to.equal(0);
|
||||
expect(@(system(detachInvocation.UTF8String))).to(equal(@0));
|
||||
}];
|
||||
|
||||
return [NSURL fileURLWithPath:path isDirectory:YES];
|
||||
}
|
||||
|
||||
- (BOOL)isRunningOnTravis {
|
||||
return NSProcessInfo.processInfo.environment[@"TRAVIS"] != nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma clang diagnostic pop
|
||||
+66
-60
@@ -6,10 +6,16 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "Squirrel-Constants.h"
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
SpecBegin(SQRLCodeSignature)
|
||||
#import "SQRLCodeSignature.h"
|
||||
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
|
||||
QuickSpecBegin(SQRLCodeSignatureSpec)
|
||||
|
||||
__block NSBundle *bundle;
|
||||
__block void (^corruptURL)(NSURL *URL);
|
||||
@@ -18,26 +24,26 @@ beforeEach(^{
|
||||
bundle = self.testApplicationBundle;
|
||||
|
||||
corruptURL = ^(NSURL *URL) {
|
||||
expect([@"this bundle is corrupted, yo" writeToURL:bundle.executableURL atomically:YES encoding:NSUTF8StringEncoding error:NULL]).to.beTruthy();
|
||||
expect(@([@"this bundle is corrupted, yo" writeToURL:bundle.executableURL atomically:YES encoding:NSUTF8StringEncoding error:NULL])).to(beTruthy());
|
||||
};
|
||||
});
|
||||
|
||||
it(@"should verify a valid bundle", ^{
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
});
|
||||
|
||||
it(@"should fail to verify with different code signing requirements", ^{
|
||||
NSError *error = nil;
|
||||
SQRLCodeSignature *verifier = [SQRLCodeSignature currentApplicationSignature:&error];
|
||||
expect(verifier).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
SQRLCodeSignature *signature = [SQRLCodeSignature currentApplicationSignature:&error];
|
||||
expect(signature).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
|
||||
BOOL success = [[verifier verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(error).notTo.beNil();
|
||||
BOOL success = [[signature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(error).notTo(beNil());
|
||||
});
|
||||
|
||||
describe(@"code signature changes", ^{
|
||||
@@ -48,15 +54,15 @@ describe(@"code signature changes", ^{
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a missing code signature", ^{
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:codeSignatureURL error:NULL]).to.beTruthy();
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:codeSignatureURL error:NULL])).to(beTruthy());
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a corrupt code signature", ^{
|
||||
@@ -64,25 +70,25 @@ describe(@"code signature changes", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"main executable changes", ^{
|
||||
it(@"should fail to verify a bundle with a missing executable", ^{
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:bundle.executableURL error:NULL]).to.beTruthy();
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:bundle.executableURL error:NULL])).to(beTruthy());
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorCouldNotCreateStaticCode);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorCouldNotCreateStaticCode)));
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a corrupt executable", ^{
|
||||
@@ -90,11 +96,11 @@ describe(@"main executable changes", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -103,19 +109,19 @@ describe(@"helper executable changes", ^{
|
||||
|
||||
beforeEach(^{
|
||||
helperURL = [bundle URLForAuxiliaryExecutable:@"unused-helper"];
|
||||
expect(helperURL).notTo.beNil();
|
||||
expect(helperURL).notTo(beNil());
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a missing helper", ^{
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:helperURL error:NULL]).to.beTruthy();
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:helperURL error:NULL])).to(beTruthy());
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a corrupt helper", ^{
|
||||
@@ -123,11 +129,11 @@ describe(@"helper executable changes", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -136,19 +142,19 @@ describe(@"resource changes", ^{
|
||||
|
||||
beforeEach(^{
|
||||
resourceURL = [bundle URLForResource:@"MainMenu" withExtension:@"nib"];
|
||||
expect(resourceURL).notTo.beNil();
|
||||
expect(resourceURL).notTo(beNil());
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a missing resource", ^{
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:resourceURL error:NULL]).to.beTruthy();
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:resourceURL error:NULL])).to(beTruthy());
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a corrupt resource", ^{
|
||||
@@ -156,11 +162,11 @@ describe(@"resource changes", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -172,15 +178,15 @@ describe(@"framework changes", ^{
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a missing framework", ^{
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:frameworkURL error:NULL]).to.beTruthy();
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:frameworkURL error:NULL])).to(beTruthy());
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a corrupt framework", ^{
|
||||
@@ -188,12 +194,12 @@ describe(@"framework changes", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
});
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
QuickSpecEnd
|
||||
@@ -1,115 +0,0 @@
|
||||
//
|
||||
// SQRLDeepCodesignSpec.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 2013-09-05.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
SpecBegin(SQRLDeepCodesign)
|
||||
|
||||
NSMutableDictionary * (^environmentSuitableForChildProcess)(void) = ^ {
|
||||
// Remove environment variables that configure the Obj-C runtime
|
||||
// Specifically OBJC_DISABLE_GC so that child processes aren't forced to
|
||||
// adopt the GC preference of the test suite
|
||||
NSMutableDictionary *environment = [NSProcessInfo.processInfo.environment mutableCopy];
|
||||
NSSet *objcEnvironmentVariables = [environment keysOfEntriesPassingTest:^(NSString *variable, id obj, BOOL *stop) {
|
||||
return [variable hasPrefix:@"OBJC"];
|
||||
}];
|
||||
[environment removeObjectsForKeys:objcEnvironmentVariables.allObjects];
|
||||
return environment;
|
||||
};
|
||||
|
||||
NSTask * (^codesignTaskWithArguments)(NSArray *) = ^ (NSArray *arguments) {
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
task.launchPath = @"/usr/bin/xcrun";
|
||||
task.arguments = [@[ @"codesign" ] arrayByAddingObjectsFromArray:arguments];
|
||||
task.environment = environmentSuitableForChildProcess();
|
||||
return task;
|
||||
};
|
||||
|
||||
void (^resignTestApplicationPreserveEverythingButTheRequirements)(void) = ^{
|
||||
NSURL *testApplicationLocation = self.testApplicationURL;
|
||||
|
||||
NSTask *resignCodesignTask = codesignTaskWithArguments(@[
|
||||
@"--sign", @"-",
|
||||
@"--force",
|
||||
@"--verbose=4",
|
||||
@"--preserve-metadata=identifier,entitlements,resource-rules",
|
||||
testApplicationLocation.path,
|
||||
]);
|
||||
|
||||
[resignCodesignTask launch];
|
||||
[resignCodesignTask waitUntilExit];
|
||||
|
||||
expect(resignCodesignTask.terminationStatus).to.equal(0);
|
||||
};
|
||||
|
||||
void (^deepCodesignTestApplication)(void) = ^{
|
||||
NSURL *testApplicationLocation = self.testApplicationURL;
|
||||
|
||||
NSBundle *testsBundle = [NSBundle bundleForClass:self.class];
|
||||
NSURL *deepCodesignLocation = [testsBundle URLForResource:@"deep-codesign" withExtension:nil];
|
||||
|
||||
NSNumber *executable = nil;
|
||||
NSError *executableError = nil;
|
||||
BOOL getExecutable = [deepCodesignLocation getResourceValue:&executable forKey:NSURLIsExecutableKey error:&executableError];
|
||||
expect(getExecutable).to.beTruthy();
|
||||
expect(executable.boolValue).to.beTruthy();
|
||||
expect(executableError).to.beNil();
|
||||
|
||||
NSTask *deepCodesignTask = [[NSTask alloc] init];
|
||||
deepCodesignTask.launchPath = deepCodesignLocation.path;
|
||||
NSMutableDictionary *environment = environmentSuitableForChildProcess();
|
||||
[environment addEntriesFromDictionary:@{
|
||||
@"CODE_SIGN_IDENTITY": @"-",
|
||||
@"CONFIGURATION_BUILD_DIR": testApplicationLocation.URLByDeletingLastPathComponent.path,
|
||||
@"FULL_PRODUCT_NAME": testApplicationLocation.lastPathComponent,
|
||||
}];
|
||||
deepCodesignTask.environment = environment;
|
||||
|
||||
[deepCodesignTask launch];
|
||||
[deepCodesignTask waitUntilExit];
|
||||
|
||||
expect(deepCodesignTask.terminationStatus).to.equal(0);
|
||||
|
||||
/*
|
||||
By signing test application's contents, which are covered by test
|
||||
application's ResourceRules it's signature becomes invalid. Usually,
|
||||
Xcode would sign the application after deep-codesign has run so the
|
||||
signature would include the _signed_ child resources which are covered
|
||||
by test application's ResourceRules
|
||||
|
||||
test application is already signed, so we need to manually resign it
|
||||
|
||||
deep-codesign preserves the requirements, we can't use it to resign the
|
||||
root target, the new signing identity wouldn't verify against the
|
||||
original designated requirement
|
||||
*/
|
||||
resignTestApplicationPreserveEverythingButTheRequirements();
|
||||
};
|
||||
|
||||
BOOL (^deepVerify)(void) = ^ BOOL {
|
||||
NSTask *deepVerifyTask = codesignTaskWithArguments(@[
|
||||
@"--deep-verify",
|
||||
@"--verbose=4",
|
||||
self.testApplicationURL.path
|
||||
]);
|
||||
|
||||
[deepVerifyTask launch];
|
||||
[deepVerifyTask waitUntilExit];
|
||||
|
||||
return deepVerifyTask.terminationStatus == 0;
|
||||
};
|
||||
|
||||
it(@"should deep sign the test application", ^{
|
||||
deepCodesignTestApplication();
|
||||
});
|
||||
|
||||
it(@"should deep verify after signing", ^{
|
||||
expect(deepVerify()).to.beFalsy();
|
||||
deepCodesignTestApplication();
|
||||
expect(deepVerify()).to.beTruthy();
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
@@ -6,39 +6,44 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLDirectoryManager.h"
|
||||
|
||||
SpecBegin(SQRLDirectoryManager)
|
||||
QuickSpecBegin(SQRLDirectoryManagerSpec)
|
||||
|
||||
__block NSString *otestIdentifier;
|
||||
|
||||
beforeEach(^{
|
||||
otestIdentifier = NSRunningApplication.currentApplication.localizedName;
|
||||
expect(otestIdentifier).notTo.beNil();
|
||||
otestIdentifier = NSProcessInfo.processInfo.environment[@"FORCE_APP_IDENTIFIER"];
|
||||
expect(otestIdentifier).notTo(beNil());
|
||||
});
|
||||
|
||||
it(@"should initialize", ^{
|
||||
SQRLDirectoryManager *manager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:otestIdentifier];
|
||||
expect(manager).notTo.beNil();
|
||||
expect(manager).notTo(beNil());
|
||||
});
|
||||
|
||||
it(@"should create a manager for the current app", ^{
|
||||
SQRLDirectoryManager *manager = SQRLDirectoryManager.currentApplicationManager;
|
||||
expect(manager).notTo.beNil();
|
||||
expect(manager).to.equal([[SQRLDirectoryManager alloc] initWithApplicationIdentifier:otestIdentifier]);
|
||||
expect(manager).notTo(beNil());
|
||||
expect(manager).to(equal([[SQRLDirectoryManager alloc] initWithApplicationIdentifier:otestIdentifier]));
|
||||
});
|
||||
|
||||
it(@"should send an Application Support URL", ^{
|
||||
SQRLDirectoryManager *manager = SQRLDirectoryManager.currentApplicationManager;
|
||||
|
||||
NSError *error = nil;
|
||||
NSURL *appSupportURL = [[manager applicationSupportURL] firstOrDefault:nil success:NULL error:&error];
|
||||
expect(appSupportURL).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
NSURL *appSupportURL = [[manager storageURL] firstOrDefault:nil success:NULL error:&error];
|
||||
expect(appSupportURL).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
|
||||
__block BOOL directory = NO;
|
||||
expect([NSFileManager.defaultManager fileExistsAtPath:appSupportURL.path isDirectory:&directory]).to.beTruthy();
|
||||
expect(directory).to.beTruthy();
|
||||
expect(@([NSFileManager.defaultManager fileExistsAtPath:appSupportURL.path isDirectory:&directory])).to(beTruthy());
|
||||
expect(@(directory)).to(beTruthy());
|
||||
});
|
||||
|
||||
it(@"should send a ShipIt state URL", ^{
|
||||
@@ -46,8 +51,8 @@ it(@"should send a ShipIt state URL", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
NSURL *stateURL = [[manager shipItStateURL] firstOrDefault:nil success:NULL error:&error];
|
||||
expect(stateURL).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
expect(stateURL).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
QuickSpecEnd
|
||||
|
||||
@@ -6,13 +6,32 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLInstaller.h"
|
||||
#import "SQRLShipItLauncher.h"
|
||||
#import "SQRLShipItState.h"
|
||||
#import "SQRLInstaller+Private.h"
|
||||
#import "SQRLInstallerOwnedBundle.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
|
||||
SpecBegin(SQRLInstaller)
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
|
||||
QuickSpecBegin(SQRLInstallerSpec)
|
||||
|
||||
mode_t (^modeOfURL)(NSURL *) = ^ mode_t (NSURL *fileURL) {
|
||||
NSFileSecurity *fileSecurity = nil;
|
||||
BOOL success = [fileURL getResourceValue:&fileSecurity forKey:NSURLFileSecurityKey error:NULL];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(fileSecurity).notTo(beNil());
|
||||
|
||||
__block mode_t mode;
|
||||
expect(@(CFFileSecurityGetMode((__bridge CFFileSecurityRef)fileSecurity, &mode))).to(beTruthy());
|
||||
|
||||
return mode & (S_IRWXU | S_IRWXG | S_IRWXO);
|
||||
};
|
||||
|
||||
__block NSURL *updateURL;
|
||||
|
||||
@@ -20,102 +39,148 @@ beforeEach(^{
|
||||
updateURL = [self createTestApplicationUpdate];
|
||||
});
|
||||
|
||||
it(@"should install an update", ^{
|
||||
SQRLShipItState *state = [[SQRLShipItState alloc] initWithTargetBundleURL:self.testApplicationURL updateBundleURL:updateURL bundleIdentifier:nil codeSignature:self.testApplicationSignature];
|
||||
expect([[state writeUsingURL:self.shipItDirectoryManager.shipItStateURL] waitUntilCompleted:NULL]).to.beTruthy();
|
||||
it(@"should install an update using ShipIt", ^{
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
|
||||
[self launchShipIt];
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
});
|
||||
|
||||
it(@"should install an update in process", ^{
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
|
||||
[self installWithRequest:request remote:NO];
|
||||
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
});
|
||||
|
||||
it(@"should install an update and relaunch", ^{
|
||||
NSString *bundleIdentifier = @"com.github.Squirrel.TestApplication";
|
||||
NSArray *apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleIdentifier];
|
||||
expect(apps.count).to.equal(0);
|
||||
expect(@(apps.count)).to(equal(@0));
|
||||
|
||||
SQRLShipItState *state = [[SQRLShipItState alloc] initWithTargetBundleURL:self.testApplicationURL updateBundleURL:updateURL bundleIdentifier:nil codeSignature:self.testApplicationSignature];
|
||||
state.relaunchAfterInstallation = YES;
|
||||
expect([[state writeUsingURL:self.shipItDirectoryManager.shipItStateURL] waitUntilCompleted:NULL]).to.beTruthy();
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:YES useUpdateBundleName:NO];
|
||||
|
||||
[self launchShipIt];
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
expect([NSRunningApplication runningApplicationsWithBundleIdentifier:bundleIdentifier].count).will.equal(1);
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
expect(@([NSRunningApplication runningApplicationsWithBundleIdentifier:bundleIdentifier].count)).toEventually(equal(@1));
|
||||
});
|
||||
|
||||
it(@"should install an update from another volume", ^{
|
||||
NSURL *diskImageURL = [self createAndMountDiskImageNamed:@"TestApplication 2.1" fromDirectory:updateURL.URLByDeletingLastPathComponent];
|
||||
updateURL = [diskImageURL URLByAppendingPathComponent:updateURL.lastPathComponent];
|
||||
|
||||
SQRLShipItState *state = [[SQRLShipItState alloc] initWithTargetBundleURL:self.testApplicationURL updateBundleURL:updateURL bundleIdentifier:nil codeSignature:self.testApplicationSignature];
|
||||
expect([[state writeUsingURL:self.shipItDirectoryManager.shipItStateURL] waitUntilCompleted:NULL]).to.beTruthy();
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
|
||||
[self launchShipIt];
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
});
|
||||
|
||||
it(@"should install an update to another volume", ^{
|
||||
NSURL *diskImageURL = [self createAndMountDiskImageNamed:@"TestApplication" fromDirectory:self.testApplicationURL.URLByDeletingLastPathComponent];
|
||||
NSURL *targetURL = [diskImageURL URLByAppendingPathComponent:self.testApplicationURL.lastPathComponent];
|
||||
|
||||
SQRLShipItState *state = [[SQRLShipItState alloc] initWithTargetBundleURL:targetURL updateBundleURL:updateURL bundleIdentifier:nil codeSignature:self.testApplicationSignature];
|
||||
expect([[state writeUsingURL:self.shipItDirectoryManager.shipItStateURL] waitUntilCompleted:NULL]).to.beTruthy();
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:targetURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
|
||||
[self launchShipIt];
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
NSURL *plistURL = [targetURL URLByAppendingPathComponent:@"Contents/Info.plist"];
|
||||
expect([NSDictionary dictionaryWithContentsOfURL:plistURL][SQRLBundleShortVersionStringKey]).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
expect([NSDictionary dictionaryWithContentsOfURL:plistURL][SQRLBundleShortVersionStringKey]).withTimeout(SQRLLongTimeout).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
});
|
||||
|
||||
it(@"should install an update in process", ^{
|
||||
SQRLShipItState *state = [[SQRLShipItState alloc] initWithTargetBundleURL:self.testApplicationURL updateBundleURL:updateURL bundleIdentifier:nil codeSignature:self.testApplicationSignature];
|
||||
state.installerState = SQRLInstallerStateClearingQuarantine;
|
||||
describe(@"with backup restoration", ^{
|
||||
__block NSURL *targetURL;
|
||||
|
||||
SQRLInstaller *installer = [[SQRLInstaller alloc] initWithDirectoryManager:SQRLDirectoryManager.currentApplicationManager];
|
||||
expect(installer).notTo.beNil();
|
||||
beforeEach(^{
|
||||
targetURL = self.testApplicationURL;
|
||||
|
||||
NSError *installError = nil;
|
||||
BOOL install = [[installer.installUpdateCommand execute:state] asynchronouslyWaitUntilCompleted:&installError];
|
||||
expect(install).to.beTruthy();
|
||||
expect(installError).to.beNil();
|
||||
NSURL *copiedTargetURL = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"TestApplication Target.app"];
|
||||
expect(@([NSFileManager.defaultManager moveItemAtURL:targetURL toURL:copiedTargetURL error:NULL])).to(beTruthy());
|
||||
|
||||
SQRLCodeSignature *codeSignature = self.testApplicationSignature;
|
||||
|
||||
SQRLInstallerOwnedBundle *ownedBundle = [[SQRLInstallerOwnedBundle alloc] initWithOriginalURL:targetURL temporaryURL:copiedTargetURL codeSignature:codeSignature];
|
||||
NSData *ownedBundleArchive = [NSKeyedArchiver archivedDataWithRootObject:ownedBundle];
|
||||
expect(ownedBundleArchive).notTo(beNil());
|
||||
|
||||
// Set up ShipIt's preferences like it paused in the middle of an
|
||||
// installation.
|
||||
NSString *applicationIdentifier = self.shipItDirectoryManager.applicationIdentifier;
|
||||
|
||||
CFPreferencesSetValue((__bridge CFStringRef)SQRLShipItInstallationAttemptsKey, (__bridge CFPropertyListRef)@(4), (__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
CFPreferencesSetValue((__bridge CFStringRef)SQRLInstallerOwnedBundleKey, (__bridge CFDataRef)ownedBundleArchive, (__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
|
||||
BOOL synchronized = CFPreferencesSynchronize((__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
expect(@(synchronized)).to(beTruthy());
|
||||
});
|
||||
|
||||
it(@"should not install an update after too many attempts", ^{
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:targetURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
__block NSError *error;
|
||||
expect(@([[self.testApplicationSignature verifyBundleAtURL:targetURL] waitUntilCompleted:&error])).toEventually(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
expect(self.testApplicationBundleVersion).to(equal(SQRLTestApplicationOriginalShortVersionString));
|
||||
});
|
||||
|
||||
it(@"should relaunch even after failing to install an update", ^{
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:targetURL bundleIdentifier:nil launchAfterInstallation:YES useUpdateBundleName:NO];
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
expect(@([NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.github.Squirrel.TestApplication"].count)).toEventually(equal(@1));
|
||||
|
||||
__block NSError *error;
|
||||
expect(@([[self.testApplicationSignature verifyBundleAtURL:targetURL] waitUntilCompleted:&error])).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
expect(self.testApplicationBundleVersion).to(equal(SQRLTestApplicationOriginalShortVersionString));
|
||||
});
|
||||
});
|
||||
|
||||
it(@"should not install an update after too many attempts", ^{
|
||||
NSURL *targetURL = self.testApplicationURL;
|
||||
NSURL *backupURL = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"TestApplication.app.bak"];
|
||||
expect([NSFileManager.defaultManager moveItemAtURL:targetURL toURL:backupURL error:NULL]).to.beTruthy();
|
||||
it(@"should disallow writing the updated application except by the owner", ^{
|
||||
NSString *command = [NSString stringWithFormat:@"chmod -R 0777 '%@'", updateURL.path];
|
||||
expect(@(system(command.UTF8String))).to(equal(@0));
|
||||
|
||||
SQRLShipItState *state = [[SQRLShipItState alloc] initWithTargetBundleURL:targetURL updateBundleURL:updateURL bundleIdentifier:nil codeSignature:self.testApplicationSignature];
|
||||
state.backupBundleURL = backupURL;
|
||||
state.installerState = SQRLInstallerStateInstalling;
|
||||
state.installationStateAttempt = 4;
|
||||
expect([[state writeUsingURL:self.shipItDirectoryManager.shipItStateURL] waitUntilCompleted:NULL]).to.beTruthy();
|
||||
expect(@(modeOfURL(updateURL))).to(equal(@0777));
|
||||
expect(@(modeOfURL([updateURL URLByAppendingPathComponent:@"Contents/MacOS/TestApplication"]))).to(equal(@0777));
|
||||
|
||||
[self launchShipIt];
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
|
||||
// No update should've been installed, and the application should be
|
||||
// restored from the backup.
|
||||
__block NSError *error = nil;
|
||||
expect([[self.testApplicationSignature verifyBundleAtURL:targetURL] waitUntilCompleted:&error]).will.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
expect(self.testApplicationBundleVersion).to.equal(SQRLTestApplicationOriginalShortVersionString);
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
|
||||
expect(@(modeOfURL(self.testApplicationURL))).to(equal(@0755));
|
||||
expect(@(modeOfURL([self.testApplicationURL URLByAppendingPathComponent:@"Contents/MacOS/TestApplication"]))).to(equal(@0755));
|
||||
});
|
||||
|
||||
describe(@"signal handling", ^{
|
||||
__block NSURL *targetURL;
|
||||
|
||||
void (^verifyUpdate)(void) = ^{
|
||||
// Wait up to the launchd throttle interval, then verify that ShipIt
|
||||
// relaunched and finished installing the update.
|
||||
expect(self.testApplicationBundleVersion).withTimeout(SQRLLongTimeout).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
|
||||
NSError *error;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:targetURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
};
|
||||
|
||||
beforeEach(^{
|
||||
// Copied so that we don't recreate the TestApplication bundle by
|
||||
// accessing the property.
|
||||
targetURL = self.testApplicationURL;
|
||||
|
||||
SQRLShipItState *state = [[SQRLShipItState alloc] initWithTargetBundleURL:self.testApplicationURL updateBundleURL:updateURL bundleIdentifier:nil codeSignature:self.testApplicationSignature];
|
||||
expect([[state writeUsingURL:self.shipItDirectoryManager.shipItStateURL] waitUntilCompleted:NULL]).to.beTruthy();
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
|
||||
[self launchShipIt];
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
// Apply a random delay before sending the termination signal, to
|
||||
// fuzz out race conditions.
|
||||
@@ -123,45 +188,42 @@ describe(@"signal handling", ^{
|
||||
[NSThread sleepForTimeInterval:delay];
|
||||
});
|
||||
|
||||
afterEach(^{
|
||||
// Wait up to the launchd throttle interval, then verify that ShipIt
|
||||
// relaunched and finished installing the update.
|
||||
Expecta.asynchronousTestTimeout = 5;
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:targetURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should handle SIGHUP", ^{
|
||||
system("killall -v -HUP ShipIt");
|
||||
system("killall -HUP ShipIt");
|
||||
verifyUpdate();
|
||||
});
|
||||
|
||||
it(@"should handle SIGTERM", ^{
|
||||
system("killall -v -TERM ShipIt");
|
||||
system("killall -TERM ShipIt");
|
||||
verifyUpdate();
|
||||
});
|
||||
|
||||
it(@"should handle SIGINT", ^{
|
||||
system("killall -v -INT ShipIt");
|
||||
system("killall -INT ShipIt");
|
||||
verifyUpdate();
|
||||
});
|
||||
|
||||
it(@"should handle SIGQUIT", ^{
|
||||
system("killall -v -QUIT ShipIt");
|
||||
system("killall -QUIT ShipIt");
|
||||
verifyUpdate();
|
||||
});
|
||||
|
||||
it(@"should handle SIGKILL", ^{
|
||||
// SIGKILL is unique in that it'll always terminate ShipIt, so send it
|
||||
// a few times to really test resumption.
|
||||
for (int i = 0; i < 3; i++) {
|
||||
system("killall -v -KILL ShipIt");
|
||||
// a couple times to really test resumption.
|
||||
//
|
||||
// Two SIGKILL signals means that it'll be launched three times (which
|
||||
// matches the maximum number of attempts per state).
|
||||
for (int i = 0; i < 2; i++) {
|
||||
system("killall -KILL ShipIt");
|
||||
|
||||
// Wait at least for the launchd throttle interval.
|
||||
NSTimeInterval delay = 2 + (arc4random_uniform(100) / 1000.0);
|
||||
[NSThread sleepForTimeInterval:delay];
|
||||
}
|
||||
|
||||
verifyUpdate();
|
||||
});
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
QuickSpecEnd
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
//
|
||||
// SQRLShipItStateSpec.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-10-09.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
|
||||
QuickSpecBegin(SQRLShipItRequestSpec)
|
||||
|
||||
__block SQRLDirectoryManager *directoryManager;
|
||||
__block SQRLShipItRequest *request;
|
||||
|
||||
beforeEach(^{
|
||||
directoryManager = SQRLDirectoryManager.currentApplicationManager;
|
||||
|
||||
NSURL *updateURL = [self createTestApplicationUpdate];
|
||||
request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
expect(request).notTo(beNil());
|
||||
|
||||
expect(request.targetBundleURL).to(equal(self.testApplicationURL));
|
||||
expect(request.updateBundleURL).to(equal(updateURL));
|
||||
expect(request.bundleIdentifier).to(beNil());
|
||||
expect(@(request.launchAfterInstallation)).to(beFalsy());
|
||||
});
|
||||
|
||||
afterEach(^{
|
||||
NSURL *stateURL = [[directoryManager shipItStateURL] first];
|
||||
expect(stateURL).notTo(beNil());
|
||||
|
||||
[NSFileManager.defaultManager removeItemAtURL:stateURL error:NULL];
|
||||
});
|
||||
|
||||
it(@"should copy", ^{
|
||||
SQRLShipItRequest *requestCopy = [request copy];
|
||||
expect(requestCopy).to(equal(request));
|
||||
expect(requestCopy).notTo(beIdenticalTo(request));
|
||||
});
|
||||
|
||||
it(@"should fail to read state when no file exists yet", ^{
|
||||
NSError *error;
|
||||
BOOL success = [[SQRLShipItRequest readUsingURL:directoryManager.shipItStateURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(error).notTo(beNil());
|
||||
});
|
||||
|
||||
it(@"should write and read state to disk", ^{
|
||||
NSError *error;
|
||||
BOOL success = [[request writeUsingURL:directoryManager.shipItStateURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
SQRLShipItRequest *readRequest = [[SQRLShipItRequest readUsingURL:directoryManager.shipItStateURL] firstOrDefault:nil success:&success error:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
expect(readRequest).to(equal(request));
|
||||
});
|
||||
|
||||
it(@"should fail gracefully with archives encoding a different class", ^{
|
||||
NSURL *archiveLocation = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"archive"];
|
||||
|
||||
NSError *error;
|
||||
BOOL write = [[NSKeyedArchiver archivedDataWithRootObject:@"rogue object"] writeToURL:archiveLocation atomically:YES];
|
||||
expect(@(write)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
BOOL success = NO;
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest readUsingURL:[RACSignal return:archiveLocation]] firstOrDefault:nil success:&success error:&error];
|
||||
expect(request).to(beNil());
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(error.domain).to(equal(SQRLShipItRequestErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLShipItRequestErrorUnarchiving)));
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
@@ -1,63 +0,0 @@
|
||||
//
|
||||
// SQRLShipItStateSpec.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-10-09.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLShipItState.h"
|
||||
|
||||
SpecBegin(SQRLShipItState)
|
||||
|
||||
__block SQRLDirectoryManager *directoryManager;
|
||||
__block SQRLShipItState *state;
|
||||
|
||||
beforeEach(^{
|
||||
directoryManager = SQRLDirectoryManager.currentApplicationManager;
|
||||
|
||||
NSURL *updateURL = [self createTestApplicationUpdate];
|
||||
state = [[SQRLShipItState alloc] initWithTargetBundleURL:self.testApplicationURL updateBundleURL:updateURL bundleIdentifier:nil codeSignature:self.testApplicationSignature];
|
||||
expect(state).notTo.beNil();
|
||||
|
||||
expect(state.targetBundleURL).to.equal(self.testApplicationURL);
|
||||
expect(state.updateBundleURL).to.equal(updateURL);
|
||||
expect(state.bundleIdentifier).to.beNil();
|
||||
expect(state.codeSignature).to.equal(self.testApplicationSignature);
|
||||
});
|
||||
|
||||
afterEach(^{
|
||||
NSURL *stateURL = [[directoryManager shipItStateURL] firstOrDefault:nil success:NULL error:NULL];
|
||||
expect(stateURL).notTo.beNil();
|
||||
|
||||
[NSFileManager.defaultManager removeItemAtURL:stateURL error:NULL];
|
||||
});
|
||||
|
||||
it(@"should copy", ^{
|
||||
SQRLShipItState *stateCopy = [state copy];
|
||||
expect(stateCopy).to.equal(state);
|
||||
expect(stateCopy).notTo.beIdenticalTo(state);
|
||||
});
|
||||
|
||||
it(@"should fail to read state when no file exists yet", ^{
|
||||
NSError *error = nil;
|
||||
BOOL success = [[SQRLShipItState readUsingURL:directoryManager.shipItStateURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(error).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should write and read state", ^{
|
||||
NSError *error = nil;
|
||||
BOOL success = [[state writeUsingURL:directoryManager.shipItStateURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
SQRLShipItState *readState = [[SQRLShipItState readUsingURL:directoryManager.shipItStateURL] firstOrDefault:nil success:&success error:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(readState).to.equal(state);
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
@@ -6,15 +6,22 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLTerminationListener.h"
|
||||
|
||||
SpecBegin(SQRLTerminationListener)
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
|
||||
QuickSpecBegin(SQRLTerminationListenerSpec)
|
||||
|
||||
__block SQRLTerminationListener *listener;
|
||||
|
||||
beforeEach(^{
|
||||
listener = [[SQRLTerminationListener alloc] initWithURL:self.testApplicationURL bundleIdentifier:self.testApplicationBundle.bundleIdentifier];
|
||||
expect(listener).notTo.beNil();
|
||||
expect(listener).notTo(beNil());
|
||||
});
|
||||
|
||||
it(@"should complete immediately when the app is not running", ^{
|
||||
@@ -23,10 +30,12 @@ it(@"should complete immediately when the app is not running", ^{
|
||||
completed = YES;
|
||||
}];
|
||||
|
||||
expect(completed).to.beTruthy();
|
||||
expect(@(completed)).to(beTruthy());
|
||||
});
|
||||
|
||||
it(@"should wait until one instance terminates", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSRunningApplication *app = [self launchTestApplicationWithEnvironment:nil];
|
||||
|
||||
__block NSRunningApplication *observedApp = nil;
|
||||
@@ -37,14 +46,17 @@ it(@"should wait until one instance terminates", ^{
|
||||
completed = YES;
|
||||
}];
|
||||
|
||||
expect(observedApp).will.equal(app);
|
||||
expect(completed).to.beFalsy();
|
||||
expect(observedApp).toEventually(equal(app));
|
||||
expect(@(completed)).to(beFalsy());
|
||||
|
||||
expect([app terminate]).to.beTruthy();
|
||||
expect(completed).will.beTruthy();
|
||||
[app forceTerminate];
|
||||
expect(@(app.terminated)).toEventually(beTruthy());
|
||||
expect(@(completed)).toEventually(beTruthy());
|
||||
});
|
||||
|
||||
it(@"should wait until multiple instances terminate", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSRunningApplication *app1 = [self launchTestApplicationWithEnvironment:nil];
|
||||
NSRunningApplication *app2 = [self launchTestApplicationWithEnvironment:nil];
|
||||
|
||||
@@ -53,13 +65,15 @@ it(@"should wait until multiple instances terminate", ^{
|
||||
completed = YES;
|
||||
}];
|
||||
|
||||
expect(completed).to.beFalsy();
|
||||
expect(@(completed)).to(beFalsy());
|
||||
|
||||
expect([app1 terminate]).to.beTruthy();
|
||||
expect(completed).to.beFalsy();
|
||||
[app1 forceTerminate];
|
||||
expect(@(app1.terminated)).toEventually(beTruthy());
|
||||
expect(@(completed)).to(beFalsy());
|
||||
|
||||
expect([app2 terminate]).to.beTruthy();
|
||||
expect(completed).will.beTruthy();
|
||||
[app2 forceTerminate];
|
||||
expect(@(app2.terminated)).toEventually(beTruthy());
|
||||
expect(@(completed)).toEventually(beTruthy());
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
QuickSpecEnd
|
||||
|
||||
@@ -6,22 +6,27 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
SpecBegin(SQRLUpdate)
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
QuickSpecBegin(SQRLUpdateSpec)
|
||||
|
||||
it(@"should return nil when initialised without a url", ^{
|
||||
NSError *error = nil;
|
||||
SQRLUpdate *update = [[SQRLUpdate alloc] initWithDictionary:@{} error:&error];
|
||||
expect(update).to.beNil();
|
||||
expect(error.domain).to.equal(NSCocoaErrorDomain);
|
||||
expect(error.code).to.equal(NSKeyValueValidationError);
|
||||
expect(update).to(beNil());
|
||||
expect(error.domain).to(equal(NSCocoaErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(NSKeyValueValidationError)));
|
||||
});
|
||||
|
||||
it(@"should return nil when initialised with a url not in URL syntax", ^{
|
||||
NSError *error = nil;
|
||||
SQRLUpdate *update = [[SQRLUpdate alloc] initWithDictionary:@{ @"updateURL": [NSURL URLWithString:@"test"] } error:&error];
|
||||
expect(update).to.beNil();
|
||||
expect(error.domain).to.equal(NSCocoaErrorDomain);
|
||||
expect(error.code).to.equal(NSKeyValueValidationError);
|
||||
expect(update).to(beNil());
|
||||
expect(error.domain).to(equal(NSCocoaErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(NSKeyValueValidationError)));
|
||||
});
|
||||
|
||||
it(@"should validate release name and notes", ^{
|
||||
@@ -32,20 +37,20 @@ it(@"should validate release name and notes", ^{
|
||||
@"releaseNotes": [[NSObject alloc] init]
|
||||
} error:NULL];
|
||||
|
||||
expect(update).notTo.beNil();
|
||||
expect(update.updateURL).to.equal(updateURL);
|
||||
expect(update.releaseName).to.beNil();
|
||||
expect(update.releaseNotes).to.beNil();
|
||||
expect(update).notTo(beNil());
|
||||
expect(update.updateURL).to(equal(updateURL));
|
||||
expect(update.releaseName).to(beNil());
|
||||
expect(update.releaseNotes).to(beNil());
|
||||
});
|
||||
|
||||
it(@"should parse Central style dates", ^{
|
||||
SQRLUpdate *update = [MTLJSONAdapter modelOfClass:SQRLUpdate.class fromJSONDictionary:@{ @"url": @"http://example.com/update", @"pub_date": @"Tue Sep 17 10:24:27 -0700 2013" } error:NULL];
|
||||
expect(update.releaseDate).notTo.beNil();
|
||||
expect(update.releaseDate).to(equal([NSDate dateWithTimeIntervalSince1970:1379438667]));
|
||||
});
|
||||
|
||||
it(@"should parse ISO 8601 dates", ^{
|
||||
SQRLUpdate *update = [MTLJSONAdapter modelOfClass:SQRLUpdate.class fromJSONDictionary:@{ @"url": @"http://example.com/update", @"pub_date": @"2013-09-18T13:17:07+01:00" } error:NULL];
|
||||
expect(update.releaseDate).notTo.beNil();
|
||||
expect(update.releaseDate).to(equal([NSDate dateWithTimeIntervalSince1970:1379506627]));
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
QuickSpecEnd
|
||||
|
||||
+247
-73
@@ -6,34 +6,44 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLTestUpdate.h"
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLZipArchiver.h"
|
||||
|
||||
SpecBegin(SQRLUpdater)
|
||||
#import "OHHTTPStubs/OHHTTPStubs.h"
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
#import "SQRLTestUpdate.h"
|
||||
#import "TestAppConstants.h"
|
||||
|
||||
QuickSpecBegin(SQRLUpdaterSpec)
|
||||
|
||||
__block NSURL *JSONURL;
|
||||
|
||||
void (^writeUpdate)(SQRLUpdate *) = ^(SQRLUpdate *update) {
|
||||
NSDictionary *updateInfo = [MTLJSONAdapter JSONDictionaryFromModel:update];
|
||||
expect(updateInfo).notTo.beNil();
|
||||
expect(updateInfo).notTo(beNil());
|
||||
|
||||
NSError *error = nil;
|
||||
NSData *JSON = [NSJSONSerialization dataWithJSONObject:updateInfo options:NSJSONWritingPrettyPrinted error:&error];
|
||||
expect(JSON).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
expect(JSON).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
|
||||
BOOL success = [JSON writeToURL:JSONURL options:NSDataWritingAtomic error:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
};
|
||||
|
||||
NSURL * (^zipUpdate)(NSURL *) = ^(NSURL *updateURL) {
|
||||
NSURL *zipFolderURL = [NSFileManager.defaultManager URLForDirectory:NSItemReplacementDirectory inDomain:NSUserDomainMask appropriateForURL:self.temporaryDirectoryURL create:YES error:NULL];
|
||||
expect(zipFolderURL).notTo.beNil();
|
||||
expect(zipFolderURL).notTo(beNil());
|
||||
|
||||
NSURL *zippedUpdateURL = [[zipFolderURL URLByAppendingPathComponent:updateURL.lastPathComponent] URLByAppendingPathExtension:@"zip"];
|
||||
BOOL success = [[SQRLZipArchiver createZipArchiveAtURL:zippedUpdateURL fromDirectoryAtURL:updateURL] asynchronouslyWaitUntilCompleted:NULL];
|
||||
expect(success).to.beTruthy();
|
||||
expect(@(success)).to(beTruthy());
|
||||
|
||||
return zippedUpdateURL;
|
||||
};
|
||||
@@ -49,85 +59,249 @@ beforeEach(^{
|
||||
JSONURL = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"update.json"];
|
||||
});
|
||||
|
||||
it(@"should use the application's bundled version of Squirrel and update in-place", ^{
|
||||
NSURL *updateURL = [self createTestApplicationUpdate];
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:NULL];
|
||||
describe(@"updating", ^{
|
||||
__block NSURL *updateURL;
|
||||
|
||||
writeUpdate(update);
|
||||
beforeEach(^{
|
||||
updateURL = [self createTestApplicationUpdate];
|
||||
});
|
||||
|
||||
NSRunningApplication *app = launchWithEnvironment(nil);
|
||||
expect(app.terminated).will.beTruthy();
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
it(@"should use the application's bundled version of Squirrel and update in-place", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSError *error = nil;
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:&error];
|
||||
expect(update).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
NSRunningApplication *app = launchWithEnvironment(nil);
|
||||
expect(@(app.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
});
|
||||
|
||||
it(@"should not install a corrupt update", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSURL *codeSignatureURL = [updateURL URLByAppendingPathComponent:@"Contents/_CodeSignature"];
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:codeSignatureURL error:NULL])).to(beTruthy());
|
||||
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:NULL];
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
NSRunningApplication *app = launchWithEnvironment(nil);
|
||||
expect(@(app.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
|
||||
// Give the update some time to finish installing.
|
||||
[NSThread sleepForTimeInterval:0.2];
|
||||
expect(self.testApplicationBundleVersion).to(equal(SQRLTestApplicationOriginalShortVersionString));
|
||||
});
|
||||
|
||||
it(@"should update to the most recently enqueued job", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(self.testApplicationURL)
|
||||
} error:NULL];
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
NSRunningApplication *app = launchWithEnvironment(nil);
|
||||
|
||||
// Now that Test Application is launched, it's going to keep checking the
|
||||
// JSON URL until it has the proper release name. So we'll wait a short bit,
|
||||
// and then add the correct name in.
|
||||
//
|
||||
// This exercises ShipIt's ability to discard previous commands and
|
||||
// install an even newer update.
|
||||
[NSThread sleepForTimeInterval:0.3];
|
||||
|
||||
update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:NULL];
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
expect(@(app.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
});
|
||||
|
||||
it(@"should use the application's bundled version of Squirrel and update in-place after a significant delay", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:NULL];
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
NSTimeInterval delay = 15;
|
||||
NSRunningApplication *app = launchWithEnvironment(@{ @"SQRLUpdateDelay": [NSString stringWithFormat:@"%f", delay] });
|
||||
|
||||
expect(@(app.terminated)).withTimeout(delay + SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
});
|
||||
|
||||
describe(@"cleaning up", ^{
|
||||
__block NSURL *appSupportURL;
|
||||
__block RACSignal *updateDirectoryURLs;
|
||||
|
||||
beforeEach(^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:@"com.github.Squirrel.TestApplication.ShipIt"];
|
||||
|
||||
appSupportURL = [[directoryManager storageURL] first];
|
||||
expect(appSupportURL).notTo(beNil());
|
||||
|
||||
updateDirectoryURLs = [[RACSignal
|
||||
defer:^{
|
||||
NSArray *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:appSupportURL includingPropertiesForKeys:nil options:0 error:NULL];
|
||||
if (contents == nil) return [RACSignal empty];
|
||||
|
||||
return contents.rac_sequence.signal;
|
||||
}]
|
||||
filter:^(NSURL *directoryURL) {
|
||||
return [directoryURL.lastPathComponent hasPrefix:@"update."];
|
||||
}];
|
||||
});
|
||||
|
||||
it(@"should remove downloaded archives after updating", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSError *error = nil;
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:&error];
|
||||
|
||||
expect(update).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
NSRunningApplication *app = launchWithEnvironment(@{ @"SQRLUpdateRequestCount": @2 });
|
||||
expect([updateDirectoryURLs toArray]).toEventuallyNot(equal(@[]));
|
||||
expect(@(app.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
|
||||
expect([updateDirectoryURLs toArray]).toEventually(equal(@[]));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it(@"should not install a corrupt update", ^{
|
||||
NSURL *updateURL = [self createTestApplicationUpdate];
|
||||
NSURL *codeSignatureURL = [updateURL URLByAppendingPathComponent:@"Contents/_CodeSignature"];
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:codeSignatureURL error:NULL]).to.beTruthy();
|
||||
describe(@"response handling", ^{
|
||||
__block NSURLRequest *localRequest = nil;
|
||||
__block SQRLUpdater *updater = nil;
|
||||
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:NULL];
|
||||
beforeEach(^{
|
||||
localRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"fake://host/path"]];
|
||||
updater = [[SQRLUpdater alloc] initWithUpdateRequest:localRequest];
|
||||
});
|
||||
|
||||
writeUpdate(update);
|
||||
it(@"should return an error for non 2xx code HTTP responses", ^{
|
||||
OHHTTPStubs *stubs = [OHHTTPStubs shouldStubRequestsPassingTest:^(NSURLRequest *request) {
|
||||
return [request.URL isEqual:localRequest.URL];
|
||||
} withStubResponse:^(NSURLRequest *request) {
|
||||
return [OHHTTPStubsResponse responseWithData:nil statusCode:/* Server Error */ 500 responseTime:0 headers:nil];
|
||||
}];
|
||||
[self addCleanupBlock:^{
|
||||
[OHHTTPStubs removeRequestHandler:stubs];
|
||||
}];
|
||||
|
||||
NSRunningApplication *app = launchWithEnvironment(nil);
|
||||
expect(app.terminated).will.beTruthy();
|
||||
NSError *error = nil;
|
||||
BOOL result = [[updater.checkForUpdatesCommand execute:nil] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(@(result)).to(beFalsy());
|
||||
expect(error.domain).to(equal(SQRLUpdaterErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLUpdaterErrorInvalidServerResponse)));
|
||||
});
|
||||
|
||||
// Give the update some time to finish installing.
|
||||
[NSThread sleepForTimeInterval:0.2];
|
||||
expect(self.testApplicationBundleVersion).to.equal(SQRLTestApplicationOriginalShortVersionString);
|
||||
it(@"should return an error for non JSON data", ^{
|
||||
OHHTTPStubs *stubs = [OHHTTPStubs shouldStubRequestsPassingTest:^(NSURLRequest *request) {
|
||||
return [request.URL isEqual:localRequest.URL];
|
||||
} withStubResponse:^(NSURLRequest *request) {
|
||||
return [OHHTTPStubsResponse responseWithData:NSData.data statusCode:/* OK */ 200 responseTime:0 headers:nil];
|
||||
}];
|
||||
[self addCleanupBlock:^{
|
||||
[OHHTTPStubs removeRequestHandler:stubs];
|
||||
}];
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL result = [[updater.checkForUpdatesCommand execute:nil] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(@(result)).to(beFalsy());
|
||||
expect(error.domain).to(equal(SQRLUpdaterErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLUpdaterErrorInvalidServerBody)));
|
||||
});
|
||||
});
|
||||
|
||||
it(@"should update to the most recently enqueued job", ^{
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(self.testApplicationURL)
|
||||
} error:NULL];
|
||||
static RACSignal * (^stateNotificationListener)(void) = ^ {
|
||||
return [[[NSDistributedNotificationCenter.defaultCenter
|
||||
rac_addObserverForName:SQRLTestAppUpdaterStateTransitionNotificationName object:nil]
|
||||
map:^(NSNotification *notification) {
|
||||
return notification.userInfo[SQRLTestAppUpdaterStateKey];
|
||||
}]
|
||||
setNameWithFormat:@"stateNotificationListener"];
|
||||
};
|
||||
|
||||
writeUpdate(update);
|
||||
describe(@"state", ^{
|
||||
it(@"should transition through idle, checking and idle, when there is no update", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSRunningApplication *app = launchWithEnvironment(nil);
|
||||
NSMutableArray *states = [NSMutableArray array];
|
||||
[stateNotificationListener() subscribeNext:^(NSNumber *state) {
|
||||
[states addObject:state];
|
||||
}];
|
||||
|
||||
// Now that Test Application is launched, it's going to keep checking the
|
||||
// JSON URL until it has the proper release name. So we'll wait a short bit,
|
||||
// and then add the correct name in.
|
||||
//
|
||||
// This exercises ShipIt's ability to discard previous commands and
|
||||
// install an even newer update.
|
||||
[NSThread sleepForTimeInterval:0.3];
|
||||
NSRunningApplication *testApplication = launchWithEnvironment(nil);
|
||||
|
||||
NSURL *updateURL = [self createTestApplicationUpdate];
|
||||
update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:NULL];
|
||||
NSArray *expectedStates = @[
|
||||
@(SQRLUpdaterStateIdle),
|
||||
@(SQRLUpdaterStateCheckingForUpdate),
|
||||
@(SQRLUpdaterStateIdle),
|
||||
];
|
||||
expect(states).toEventually(equal(expectedStates));
|
||||
|
||||
writeUpdate(update);
|
||||
expect(@(testApplication.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
});
|
||||
|
||||
expect(app.terminated).will.beTruthy();
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
it(@"should transition through idle, checking, downloading and awaiting relaunch, when there is an update", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSMutableArray *states = [NSMutableArray array];
|
||||
[stateNotificationListener() subscribeNext:^(NSNumber *state) {
|
||||
[states addObject:state];
|
||||
}];
|
||||
|
||||
NSError *error;
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate([self createTestApplicationUpdate]),
|
||||
@"final": @YES,
|
||||
} error:&error];
|
||||
expect(update).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
NSRunningApplication *testApplication = launchWithEnvironment(nil);
|
||||
|
||||
NSArray *expectedStates = @[
|
||||
@(SQRLUpdaterStateIdle),
|
||||
@(SQRLUpdaterStateCheckingForUpdate),
|
||||
@(SQRLUpdaterStateDownloadingUpdate),
|
||||
@(SQRLUpdaterStateAwaitingRelaunch),
|
||||
];
|
||||
expect(states).withTimeout(SQRLLongTimeout).toEventually(equal(expectedStates));
|
||||
|
||||
expect(@(testApplication.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
});
|
||||
});
|
||||
|
||||
it(@"should use the application's bundled version of Squirrel and update in-place after a significant delay", ^{
|
||||
NSURL *updateURL = [self createTestApplicationUpdate];
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:NULL];
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
NSTimeInterval delay = 30;
|
||||
NSRunningApplication *app = launchWithEnvironment(@{ @"SQRLUpdateDelay": [NSString stringWithFormat:@"%f", delay] });
|
||||
|
||||
Expecta.asynchronousTestTimeout = delay + 3;
|
||||
expect(app.terminated).will.beTruthy();
|
||||
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
QuickSpecEnd
|
||||
|
||||
@@ -6,39 +6,44 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "SQRLZipArchiver.h"
|
||||
#import "Squirrel-Constants.h"
|
||||
|
||||
SpecBegin(SQRLZipArchiver)
|
||||
QuickSpecBegin(SQRLZipArchiverSpec)
|
||||
|
||||
it(@"should extract a zip archive created by the Finder", ^{
|
||||
NSURL *zipURL = [[NSBundle bundleForClass:self.class] URLForResource:@"TestApplication.app" withExtension:@"zip"];
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[SQRLZipArchiver unzipArchiveAtURL:zipURL intoDirectoryAtURL:self.temporaryDirectoryURL] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
NSURL *extractedAppURL = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"TestApplication 2.1.app"];
|
||||
expect([NSFileManager.defaultManager fileExistsAtPath:extractedAppURL.path]).to.beTruthy();
|
||||
expect(@([NSFileManager.defaultManager fileExistsAtPath:extractedAppURL.path])).to(beTruthy());
|
||||
|
||||
success = [[self.testApplicationSignature verifyBundleAtURL:extractedAppURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
});
|
||||
|
||||
it(@"should fail to extract a nonexistent zip archive", ^{
|
||||
NSError *error = nil;
|
||||
BOOL success = [[SQRLZipArchiver unzipArchiveAtURL:[self.temporaryDirectoryURL URLByAppendingPathComponent:@"foo.zip"] intoDirectoryAtURL:self.temporaryDirectoryURL] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(@(success)).to(beFalsy());
|
||||
|
||||
NSLog(@"%@", error);
|
||||
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLErrorDomain);
|
||||
expect(error.code).to.equal(SQRLZipArchiverShellTaskFailed);
|
||||
expect(error.userInfo[SQRLZipArchiverExitCodeErrorKey]).notTo.equal(0);
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLZipArchiverErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLZipArchiverShellTaskFailed)));
|
||||
expect(error.userInfo[SQRLZipArchiverExitCodeErrorKey]).notTo(equal(0));
|
||||
});
|
||||
|
||||
it(@"should create a zip archive readable by itself", ^{
|
||||
@@ -46,21 +51,21 @@ it(@"should create a zip archive readable by itself", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[SQRLZipArchiver createZipArchiveAtURL:zipURL fromDirectoryAtURL:self.testApplicationURL] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
expect([NSFileManager.defaultManager fileExistsAtPath:zipURL.path]).to.beTruthy();
|
||||
expect(@([NSFileManager.defaultManager fileExistsAtPath:zipURL.path])).to(beTruthy());
|
||||
|
||||
success = [[SQRLZipArchiver unzipArchiveAtURL:zipURL intoDirectoryAtURL:self.temporaryDirectoryURL] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
NSURL *extractedAppURL = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"TestApplication.app"];
|
||||
expect([NSFileManager.defaultManager fileExistsAtPath:extractedAppURL.path]).to.beTruthy();
|
||||
expect(@([NSFileManager.defaultManager fileExistsAtPath:extractedAppURL.path])).to(beTruthy());
|
||||
|
||||
success = [[self.testApplicationSignature verifyBundleAtURL:extractedAppURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
QuickSpecEnd
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.github.${PRODUCT_NAME:rfc1034identifier}</string>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
//
|
||||
// SquirrelTests-Prefix.pch
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-07-21.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#ifdef __OBJC__
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <SenTestingKit/SenTestingKit.h>
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#define SPT_SUBCLASS SQRLTestCase
|
||||
#import "Specta.h"
|
||||
|
||||
#define EXP_SHORTHAND
|
||||
#import "Expecta.h"
|
||||
|
||||
#import "SQRLTestCase.h"
|
||||
#endif
|
||||
@@ -0,0 +1,19 @@
|
||||
//
|
||||
// SwiftSpec.swift
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2014-10-14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Nimble
|
||||
import Quick
|
||||
|
||||
// Without this, the Swift stdlib won't be linked into the test target (even if
|
||||
// “Embedded Content Contains Swift Code” is enabled).
|
||||
class SwiftSpec: QuickSpec {
|
||||
override func spec() {
|
||||
expect(true).to(beTruthy())
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
/* Localized versions of Info.plist keys */
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>rules</key>
|
||||
<dict>
|
||||
<key>.*</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,22 @@
|
||||
//
|
||||
// TestAppConstants.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 05/02/2014.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
// This notification is posted to the distributed notification center when a
|
||||
// change to the `SQRLUpdater.state` property is observed.
|
||||
//
|
||||
// It is posted once on launch with the initial idle state, and then for any
|
||||
// transition thereafter.
|
||||
//
|
||||
// Yhe user info dictionary includes the new state value under the
|
||||
// `SQRLTestAppUpdaterStateKey` key.
|
||||
extern NSString * const SQRLTestAppUpdaterStateTransitionNotificationName;
|
||||
|
||||
// The state of the updater, an NSNumber.
|
||||
extern NSString * const SQRLTestAppUpdaterStateKey;
|
||||
@@ -0,0 +1,13 @@
|
||||
//
|
||||
// TestAppConstants.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 05/02/2014.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "TestAppConstants.h"
|
||||
|
||||
NSString * const SQRLTestAppUpdaterStateTransitionNotificationName = @"com.github.Squirrel.TestApplication.state-changed";
|
||||
|
||||
NSString * const SQRLTestAppUpdaterStateKey = @"state";
|
||||
@@ -12,6 +12,7 @@
|
||||
#import "SQRLTestUpdate.h"
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import "TestAppConstants.h"
|
||||
|
||||
@interface TestAppDelegate ()
|
||||
|
||||
@@ -63,8 +64,17 @@
|
||||
self.updater = [[SQRLUpdater alloc] initWithUpdateRequest:request];
|
||||
self.updater.updateClass = SQRLTestUpdate.class;
|
||||
|
||||
[RACObserve(self.updater, state) subscribeNext:^(NSNumber *state) {
|
||||
NSLog(@"State transition: %@", state);
|
||||
|
||||
[NSDistributedNotificationCenter.defaultCenter postNotificationName:SQRLTestAppUpdaterStateTransitionNotificationName object:nil userInfo:@{ SQRLTestAppUpdaterStateKey: state }];
|
||||
}];
|
||||
|
||||
__block NSUInteger updateCheckCount = 1;
|
||||
|
||||
NSInteger updateRequestCount = [NSProcessInfo.processInfo.environment[@"SQRLUpdateRequestCount"] integerValue];
|
||||
if (updateRequestCount < 1) updateRequestCount = 1;
|
||||
|
||||
[[[[[[[[[[RACSignal
|
||||
defer:^{
|
||||
NSLog(@"***** UPDATE CHECK %lu *****", (unsigned long)updateCheckCount);
|
||||
@@ -83,7 +93,7 @@
|
||||
|
||||
return testUpdate.final;
|
||||
}]
|
||||
take:1]
|
||||
take:updateRequestCount]
|
||||
doNext:^(id _) {
|
||||
NSLog(@"***** READY TO INSTALL UPDATE *****");
|
||||
}]
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<key>CFBundleIconFile</key>
|
||||
<string></string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.github.Squirrel.${PRODUCT_NAME:rfc1034identifier}</string>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
@@ -30,5 +30,7 @@
|
||||
<string>MainMenu</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>NSSupportsAutomaticTermination</key>
|
||||
<false/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
|
||||
+68
-6
@@ -1,6 +1,66 @@
|
||||
These scripts are primarily meant to support the use of
|
||||
[Janky](https://github.com/github/janky). To use them, read the contents of this
|
||||
repository into a `script` folder:
|
||||
# objc-build-scripts
|
||||
|
||||
This project is a collection of scripts created with two goals:
|
||||
|
||||
1. To standardize how Objective-C projects are bootstrapped after cloning
|
||||
1. To easily build Objective-C projects on continuous integration servers
|
||||
|
||||
## Scripts
|
||||
|
||||
Right now, there are two important scripts: [`bootstrap`](#bootstrap) and
|
||||
[`cibuild`](#cibuild). Both are Bash scripts, to maximize compatibility and
|
||||
eliminate pesky system configuration issues (like setting up a working Ruby
|
||||
environment).
|
||||
|
||||
The structure of the scripts on disk is meant to follow that of a typical Ruby
|
||||
project:
|
||||
|
||||
```
|
||||
script/
|
||||
bootstrap
|
||||
cibuild
|
||||
```
|
||||
|
||||
### bootstrap
|
||||
|
||||
This script is responsible for bootstrapping (initializing) your project after
|
||||
it's been checked out. Here, you should install or clone any dependencies that
|
||||
are required for a working build and development environment.
|
||||
|
||||
By default, the script will verify that [xctool][] is installed, then initialize
|
||||
and update submodules recursively. If any submodules contain `script/bootstrap`,
|
||||
that will be run as well.
|
||||
|
||||
To check that other tools are installed, you can set the `REQUIRED_TOOLS`
|
||||
environment variable before running `script/bootstrap`, or edit it within the
|
||||
script directly. Note that no installation is performed automatically, though
|
||||
this can always be added within your specific project.
|
||||
|
||||
### cibuild
|
||||
|
||||
This script is responsible for building the project, as you would want it built
|
||||
for continuous integration. This is preferable to putting the logic on the CI
|
||||
server itself, since it ensures that any changes are versioned along with the
|
||||
source.
|
||||
|
||||
By default, the script will run [`bootstrap`](#bootstrap), look for any Xcode
|
||||
workspace or project in the working directory, then build all targets/schemes
|
||||
(as found by `xcodebuild -list`) using [xctool][].
|
||||
|
||||
You can also specify the schemes to build by passing them into the script:
|
||||
|
||||
```sh
|
||||
script/cibuild ReactiveCocoa-Mac ReactiveCocoa-iOS
|
||||
```
|
||||
|
||||
As with the `bootstrap` script, there are several environment variables that can
|
||||
be used to customize behavior. They can be set on the command line before
|
||||
invoking the script, or the defaults changed within the script directly.
|
||||
|
||||
## Getting Started
|
||||
|
||||
To add the scripts to your project, read the contents of this repository into
|
||||
a `script` folder:
|
||||
|
||||
```
|
||||
$ git remote add objc-build-scripts https://github.com/jspahrsummers/objc-build-scripts.git
|
||||
@@ -8,13 +68,15 @@ $ git fetch objc-build-scripts
|
||||
$ git read-tree --prefix=script/ -u objc-build-scripts/master
|
||||
```
|
||||
|
||||
Then commit the changes to incorporate the scripts into your own repository's
|
||||
Then commit the changes, to incorporate the scripts into your own repository's
|
||||
history. You can also freely tweak the scripts for your specific project's
|
||||
needs.
|
||||
|
||||
To bring in upstream changes later:
|
||||
To merge in upstream changes later:
|
||||
|
||||
```
|
||||
$ git fetch -p objc-build-scripts
|
||||
$ git merge -Xsubtree=script objc-build-scripts/master
|
||||
$ git merge --ff --squash -Xsubtree=script objc-build-scripts/master
|
||||
```
|
||||
|
||||
[xctool]: https://github.com/facebook/xctool
|
||||
|
||||
+76
-7
@@ -1,11 +1,80 @@
|
||||
#!/bin/bash
|
||||
|
||||
SCRIPT_DIR=$(dirname "$0")
|
||||
cd "$SCRIPT_DIR/.."
|
||||
export SCRIPT_DIR=$(dirname "$0")
|
||||
|
||||
set -o errexit
|
||||
##
|
||||
## Configuration Variables
|
||||
##
|
||||
|
||||
echo "*** Updating submodules..."
|
||||
git submodule sync --quiet
|
||||
git submodule update --init
|
||||
git submodule foreach --recursive --quiet "git submodule sync --quiet && git submodule update --init"
|
||||
config ()
|
||||
{
|
||||
# A whitespace-separated list of executables that must be present and locatable.
|
||||
: ${REQUIRED_TOOLS="xctool"}
|
||||
|
||||
export REQUIRED_TOOLS
|
||||
}
|
||||
|
||||
##
|
||||
## Bootstrap Process
|
||||
##
|
||||
|
||||
main ()
|
||||
{
|
||||
config
|
||||
|
||||
if [ -n "$REQUIRED_TOOLS" ]
|
||||
then
|
||||
echo "*** Checking dependencies..."
|
||||
check_deps
|
||||
fi
|
||||
|
||||
local submodules=$(git submodule status)
|
||||
local result=$?
|
||||
|
||||
if [ "$result" -ne "0" ]
|
||||
then
|
||||
exit $result
|
||||
fi
|
||||
|
||||
if [ -n "$submodules" ]
|
||||
then
|
||||
echo "*** Updating submodules..."
|
||||
update_submodules
|
||||
fi
|
||||
}
|
||||
|
||||
check_deps ()
|
||||
{
|
||||
for tool in $REQUIRED_TOOLS
|
||||
do
|
||||
which -s "$tool"
|
||||
if [ "$?" -ne "0" ]
|
||||
then
|
||||
echo "*** Error: $tool not found. Please install it and bootstrap again."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
bootstrap_submodule ()
|
||||
{
|
||||
local bootstrap="script/bootstrap"
|
||||
|
||||
if [ -e "$bootstrap" ]
|
||||
then
|
||||
echo "*** Bootstrapping $name..."
|
||||
"$bootstrap" >/dev/null
|
||||
else
|
||||
update_submodules
|
||||
fi
|
||||
}
|
||||
|
||||
update_submodules ()
|
||||
{
|
||||
git submodule sync --quiet && git submodule update --init && git submodule foreach --quiet bootstrap_submodule
|
||||
}
|
||||
|
||||
export -f bootstrap_submodule
|
||||
export -f update_submodules
|
||||
|
||||
main
|
||||
|
||||
Binary file not shown.
+119
-79
@@ -1,129 +1,169 @@
|
||||
#!/bin/bash
|
||||
|
||||
SCRIPT_DIR=$(dirname "$0")
|
||||
cd "$SCRIPT_DIR/.."
|
||||
export SCRIPT_DIR=$(dirname "$0")
|
||||
|
||||
##
|
||||
## Configuration Variables
|
||||
##
|
||||
|
||||
# The build configuration to use.
|
||||
if [ -z "$XCCONFIGURATION" ]
|
||||
then
|
||||
XCCONFIGURATION="Test"
|
||||
fi
|
||||
SCHEMES="$@"
|
||||
|
||||
# The workspace to build.
|
||||
#
|
||||
# If not set and no workspace is found, the -workspace flag will not be passed
|
||||
# to xcodebuild.
|
||||
if [ -z "$XCWORKSPACE" ]
|
||||
then
|
||||
XCWORKSPACE=$(ls -d *.xcworkspace 2>/dev/null | head -n 1)
|
||||
fi
|
||||
config ()
|
||||
{
|
||||
# The workspace to build.
|
||||
#
|
||||
# If not set and no workspace is found, the -workspace flag will not be passed
|
||||
# to `xctool`.
|
||||
#
|
||||
# Only one of `XCWORKSPACE` and `XCODEPROJ` needs to be set. The former will
|
||||
# take precedence.
|
||||
: ${XCWORKSPACE=$(find_pattern "*.xcworkspace")}
|
||||
|
||||
# A bootstrap script to run before building.
|
||||
#
|
||||
# If this file does not exist, it is not considered an error.
|
||||
BOOTSTRAP="$SCRIPT_DIR/bootstrap"
|
||||
# The project to build.
|
||||
#
|
||||
# If not set and no project is found, the -project flag will not be passed
|
||||
# to `xctool`.
|
||||
#
|
||||
# Only one of `XCWORKSPACE` and `XCODEPROJ` needs to be set. The former will
|
||||
# take precedence.
|
||||
: ${XCODEPROJ=$(find_pattern "*.xcodeproj")}
|
||||
|
||||
# A whitespace-separated list of default targets or schemes to build, if none
|
||||
# are specified on the command line.
|
||||
#
|
||||
# Individual names can be quoted to avoid word splitting.
|
||||
DEFAULT_TARGETS=Squirrel
|
||||
# A bootstrap script to run before building.
|
||||
#
|
||||
# If this file does not exist, it is not considered an error.
|
||||
: ${BOOTSTRAP="$SCRIPT_DIR/bootstrap"}
|
||||
|
||||
# Extra build settings to pass to xcodebuild.
|
||||
XCODEBUILD_SETTINGS="TEST_AFTER_BUILD=YES"
|
||||
# Extra options to pass to xctool.
|
||||
: ${XCTOOL_OPTIONS="RUN_CLANG_STATIC_ANALYZER=NO"}
|
||||
|
||||
# A whitespace-separated list of default schemes to build.
|
||||
#
|
||||
# Individual names can be quoted to avoid word splitting.
|
||||
: ${SCHEMES:=Squirrel}
|
||||
|
||||
export XCWORKSPACE
|
||||
export XCODEPROJ
|
||||
export BOOTSTRAP
|
||||
export XCTOOL_OPTIONS
|
||||
export SCHEMES
|
||||
}
|
||||
|
||||
##
|
||||
## Code-signing Setup
|
||||
## Code Signing
|
||||
##
|
||||
|
||||
# A source-able file with information about the Keychain containing our
|
||||
# code-signing certificate.
|
||||
KEYCHAIN_INFO=/var/lib/jenkins/config/xcodekeychain
|
||||
setup_keychain ()
|
||||
{
|
||||
KEY_CHAIN=build.keychain
|
||||
security create-keychain -p travis $KEY_CHAIN
|
||||
|
||||
if [ -e "$KEYCHAIN_INFO" ]
|
||||
then
|
||||
# Unlock the keychain so the certificates it contains can be used for building.
|
||||
. "${KEYCHAIN_INFO}"
|
||||
security unlock-keychain -p "${XCODE_KEYCHAIN_PASSWORD}" "${XCODE_KEYCHAIN}"
|
||||
fi
|
||||
security default-keychain -s $KEY_CHAIN
|
||||
security unlock-keychain -p travis $KEY_CHAIN
|
||||
security set-keychain-settings -t 3600 -u $KEY_CHAIN
|
||||
security import script/certs.p12 -k build.keychain -P $KEY_PASSWORD -T /usr/bin/codesign
|
||||
}
|
||||
|
||||
##
|
||||
## Build Process
|
||||
##
|
||||
|
||||
if [ -z "$*" ]
|
||||
then
|
||||
# lol recursive shell script
|
||||
if [ -n "$DEFAULT_TARGETS" ]
|
||||
main ()
|
||||
{
|
||||
config
|
||||
setup_keychain
|
||||
|
||||
if [ -f "$BOOTSTRAP" ]
|
||||
then
|
||||
echo "$DEFAULT_TARGETS" | xargs "$SCRIPT_DIR/cibuild"
|
||||
else
|
||||
xcodebuild -list | awk -f "$SCRIPT_DIR/targets.awk" | xargs "$SCRIPT_DIR/cibuild"
|
||||
echo "*** Bootstrapping..."
|
||||
"$BOOTSTRAP" || exit $?
|
||||
fi
|
||||
|
||||
exit $?
|
||||
fi
|
||||
echo "*** The following schemes will be built:"
|
||||
echo "$SCHEMES" | xargs -n 1 echo " "
|
||||
echo
|
||||
|
||||
if [ -f "$BOOTSTRAP" ]
|
||||
then
|
||||
echo "*** Bootstrapping..."
|
||||
bash "$BOOTSTRAP" || exit $?
|
||||
fi
|
||||
echo "$SCHEMES" | xargs -n 1 | (
|
||||
local status=0
|
||||
|
||||
echo "*** The following targets will be built:"
|
||||
while read scheme
|
||||
do
|
||||
build_scheme "$scheme" || status=1
|
||||
done
|
||||
|
||||
for target in "$@"
|
||||
do
|
||||
echo "$target"
|
||||
done
|
||||
exit $status
|
||||
)
|
||||
}
|
||||
|
||||
echo "*** Cleaning all targets..."
|
||||
xcodebuild -alltargets clean OBJROOT="$PWD/build" SYMROOT="$PWD/build" $XCODEBUILD_SETTINGS
|
||||
|
||||
run_xcodebuild ()
|
||||
find_pattern ()
|
||||
{
|
||||
local scheme=$1
|
||||
ls -d $1 2>/dev/null | head -n 1
|
||||
}
|
||||
|
||||
run_xctool ()
|
||||
{
|
||||
if [ -n "$XCWORKSPACE" ]
|
||||
then
|
||||
xcodebuild -workspace "$XCWORKSPACE" -scheme "$scheme" -configuration "$XCCONFIGURATION" build OBJROOT="$PWD/build" SYMROOT="$PWD/build" $XCODEBUILD_SETTINGS
|
||||
xctool -workspace "$XCWORKSPACE" $XCTOOL_OPTIONS "$@" 2>&1
|
||||
elif [ -n "$XCODEPROJ" ]
|
||||
then
|
||||
xctool -project "$XCODEPROJ" $XCTOOL_OPTIONS "$@" 2>&1
|
||||
else
|
||||
xcodebuild -scheme "$scheme" -configuration "$XCCONFIGURATION" build OBJROOT="$PWD/build" SYMROOT="$PWD/build" $XCODEBUILD_SETTINGS
|
||||
echo "*** No workspace or project file found."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
local status=$?
|
||||
|
||||
return $status
|
||||
parse_build ()
|
||||
{
|
||||
awk -f "$SCRIPT_DIR/xctool.awk" 2>&1 >/dev/null
|
||||
}
|
||||
|
||||
build_scheme ()
|
||||
{
|
||||
local scheme=$1
|
||||
|
||||
run_xcodebuild "$scheme" 2>&1 | awk -f "$SCRIPT_DIR/xcodebuild.awk"
|
||||
echo "*** Cleaning $scheme..."
|
||||
run_xctool -scheme "$scheme" clean >/dev/null || exit $?
|
||||
|
||||
echo "*** Building and testing $scheme..."
|
||||
echo
|
||||
|
||||
local sdkflag=
|
||||
local action=test
|
||||
|
||||
# Determine whether we can run unit tests for this target.
|
||||
run_xctool -scheme "$scheme" run-tests | parse_build
|
||||
|
||||
local awkstatus=$?
|
||||
local xcstatus=${PIPESTATUS[0]}
|
||||
|
||||
if [ "$xcstatus" -eq "65" ]
|
||||
if [ "$awkstatus" -eq "1" ]
|
||||
then
|
||||
# This probably means that there's no scheme by that name. Give up.
|
||||
echo "*** Error building scheme $scheme -- perhaps it doesn't exist"
|
||||
elif [ "$awkstatus" -eq "1" ]
|
||||
then
|
||||
return $awkstatus
|
||||
# SDK not found, try for iphonesimulator.
|
||||
sdkflag="-sdk iphonesimulator"
|
||||
|
||||
# Determine whether the unit tests will run with iphonesimulator
|
||||
run_xctool $sdkflag -scheme "$scheme" run-tests | parse_build
|
||||
|
||||
awkstatus=$?
|
||||
|
||||
if [ "$awkstatus" -ne "0" ]
|
||||
then
|
||||
# Unit tests will not run on iphonesimulator.
|
||||
sdkflag=""
|
||||
fi
|
||||
fi
|
||||
|
||||
return $xcstatus
|
||||
if [ "$awkstatus" -ne "0" ]
|
||||
then
|
||||
# Unit tests aren't supported.
|
||||
action=build
|
||||
fi
|
||||
|
||||
run_xctool $sdkflag -scheme "$scheme" $action
|
||||
}
|
||||
|
||||
echo "*** Building..."
|
||||
export -f build_scheme
|
||||
export -f run_xctool
|
||||
export -f parse_build
|
||||
|
||||
for scheme in "$@"
|
||||
do
|
||||
build_scheme "$scheme" || exit $?
|
||||
done
|
||||
main
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
#!/usr/bin/env ruby
|
||||
|
||||
def exit_error(description)
|
||||
puts "{ \"error\": \"#{description}\" }"
|
||||
exit 1
|
||||
end
|
||||
|
||||
module Targets
|
||||
class Object
|
||||
def self.match(path)
|
||||
!File.symlink?(path)
|
||||
end
|
||||
|
||||
attr_reader :path
|
||||
|
||||
def initialize(path)
|
||||
@path = path
|
||||
end
|
||||
|
||||
def search_directories
|
||||
[]
|
||||
end
|
||||
end
|
||||
|
||||
class Bundle < Object
|
||||
def self.match(path)
|
||||
return false unless super
|
||||
|
||||
return false unless match = File.extname(path).match(/\.(.+)/)
|
||||
return match[1] == extension
|
||||
end
|
||||
|
||||
def contents_directories
|
||||
[ "Contents" ]
|
||||
end
|
||||
|
||||
def suffix_directories
|
||||
[
|
||||
"Frameworks",
|
||||
"SharedFrameworks",
|
||||
"XPCServices",
|
||||
"PlugIns",
|
||||
"Support",
|
||||
"SharedSupport",
|
||||
File.join("Library", "LoginItems"),
|
||||
File.join("Library", "LaunchServices"),
|
||||
]
|
||||
end
|
||||
|
||||
def search_directories
|
||||
contents_directories.product(suffix_directories).map do |combination|
|
||||
File.join(*combination)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
class VersionedBundle < Bundle
|
||||
def contents_directories
|
||||
contents_directories = []
|
||||
versions_directory = File.join(@path, "Versions")
|
||||
Dir.foreach(versions_directory) do |current_version|
|
||||
next if current_version.start_with?('.')
|
||||
|
||||
full_path = File.join(versions_directory, current_version)
|
||||
next if File.symlink?(full_path)
|
||||
|
||||
contents_directories << File.join("Versions", current_version)
|
||||
end
|
||||
contents_directories
|
||||
end
|
||||
end
|
||||
|
||||
class App < Bundle
|
||||
def self.extension
|
||||
"app"
|
||||
end
|
||||
end
|
||||
|
||||
class Framework < VersionedBundle
|
||||
def self.extension
|
||||
"framework"
|
||||
end
|
||||
end
|
||||
|
||||
class XPCService < Bundle
|
||||
def self.extension
|
||||
"xpc"
|
||||
end
|
||||
end
|
||||
|
||||
class Tool < Object
|
||||
def self.match(path)
|
||||
return false unless super
|
||||
return false unless File.executable?(path)
|
||||
|
||||
# Look for an __TEXT,__info_plist section
|
||||
# This contains the CFBundleIdentifier necessary for signing
|
||||
`otool -l #{path}` =~ /__info_plist/
|
||||
end
|
||||
end
|
||||
|
||||
def self.all_targets
|
||||
[ App, Framework, XPCService, Tool ]
|
||||
end
|
||||
end
|
||||
|
||||
module Codesign
|
||||
class Task
|
||||
def self.sign(target, identity)
|
||||
codesign_with_arguments([ "--sign", identity, "--force", "--preserve-metadata=identifier,entitlements,resource-rules,requirements", "--verbose", target.path ])
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
def self.codesign_with_arguments(arguments)
|
||||
$stdout.flush
|
||||
|
||||
pid = fork
|
||||
if pid.nil?
|
||||
exec("/usr/bin/xcrun", *([ "codesign" ].concat(arguments)))
|
||||
else
|
||||
Process.wait(pid)
|
||||
exit_error("codesign failed") unless $?.exitstatus == 0
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
codesign_identity = ENV['CODE_SIGN_IDENTITY']
|
||||
unless codesign_identity
|
||||
exit_error("No codesign identity provided")
|
||||
end
|
||||
|
||||
build_dir = ENV['CONFIGURATION_BUILD_DIR']
|
||||
product_name = ENV['FULL_PRODUCT_NAME']
|
||||
unless build_dir && product_name
|
||||
exit_error("Path to built product not provided")
|
||||
end
|
||||
|
||||
input_path = File.join(build_dir, product_name)
|
||||
unless File.exists?(input_path)
|
||||
exit_error("Built product doesn't exist at path provided")
|
||||
end
|
||||
|
||||
targets = [ ]
|
||||
|
||||
def match_path(path)
|
||||
Targets.all_targets.each do |target|
|
||||
return target.new(path) if target.match(path)
|
||||
end
|
||||
nil
|
||||
end
|
||||
|
||||
root_target = match_path input_path
|
||||
if root_target.nil?
|
||||
exit_error("Built product is not a known file structure, cannot deep codesign")
|
||||
end
|
||||
|
||||
# Recursion base case can't use build_dir because there can be >1 product
|
||||
paths_to_search = root_target.search_directories.map do |current_dir|
|
||||
File.join(root_target.path, current_dir)
|
||||
end
|
||||
|
||||
while paths_to_search.size > 0
|
||||
new_search_paths = []
|
||||
paths_to_search.each do |search_path|
|
||||
next unless File.directory?(search_path)
|
||||
|
||||
Dir.foreach(search_path) do |current_directory_entry|
|
||||
next if current_directory_entry.start_with?(".")
|
||||
|
||||
target = match_path(File.join(search_path, current_directory_entry))
|
||||
next if target.nil?
|
||||
|
||||
targets << target
|
||||
|
||||
new_search_paths << target.search_directories.map do |current_search_directory|
|
||||
File.join(target.path, current_search_directory)
|
||||
end
|
||||
end
|
||||
end
|
||||
paths_to_search = new_search_paths.flatten
|
||||
end
|
||||
|
||||
puts "Signing these targets:"
|
||||
puts "="*22
|
||||
print "\n"
|
||||
|
||||
# Sort into nested-most first, outer targets might include inner targets
|
||||
# in their ResourceRules
|
||||
targets = targets.sort_by do |target|
|
||||
target.path.size
|
||||
end
|
||||
targets.reverse!
|
||||
|
||||
targets.each do |target|
|
||||
puts "=> #{target.path}"
|
||||
Codesign::Task.sign(target, codesign_identity)
|
||||
end
|
||||
@@ -0,0 +1,10 @@
|
||||
BEGIN {
|
||||
FS = "\n";
|
||||
}
|
||||
|
||||
/Schemes:/ {
|
||||
while (getline && $0 != "") {
|
||||
sub(/^ +/, "");
|
||||
print "'" $0 "'";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
# Exit statuses:
|
||||
#
|
||||
# 0 - No errors found.
|
||||
# 1 - Wrong SDK. Retry with SDK `iphonesimulator`.
|
||||
# 2 - Missing target.
|
||||
|
||||
BEGIN {
|
||||
status = 0;
|
||||
}
|
||||
|
||||
{
|
||||
print;
|
||||
}
|
||||
|
||||
/Testing with the '(.+)' SDK is not yet supported/ {
|
||||
status = 1;
|
||||
}
|
||||
|
||||
/does not contain a target named/ {
|
||||
status = 2;
|
||||
}
|
||||
|
||||
END {
|
||||
exit status;
|
||||
}
|
||||
Reference in New Issue
Block a user