mirror of
https://github.com/sparkle-project/Sparkle
synced 2026-11-23 04:34:27 +00:00
Compare commits
576
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e7088fc788 | ||
|
|
54aa6f2cc2 | ||
|
|
acf758e485 | ||
|
|
ceedfba634 | ||
|
|
addedeac13 | ||
|
|
eedb0ff0dd | ||
|
|
67a7bc3d62 | ||
|
|
65d7c38ab6 | ||
|
|
5b786043c2 | ||
|
|
ca23238d59 | ||
|
|
fc1870cbd2 | ||
|
|
659aec4eaf | ||
|
|
88a197a7f0 | ||
|
|
9119d287ab | ||
|
|
7797a8f58c | ||
|
|
1f0da95e59 | ||
|
|
84a2feb0ad | ||
|
|
bbe75fc6f2 | ||
|
|
9c8e08b7ae | ||
|
|
371c51fe5a | ||
|
|
feb2ad4b64 | ||
|
|
1e75acb963 | ||
|
|
b3c69f8b8c | ||
|
|
5cd9bdccf6 | ||
|
|
12eede4123 | ||
|
|
9633a57c6c | ||
|
|
ab389260be | ||
|
|
abf70ab8dc | ||
|
|
67ebc6ff74 | ||
|
|
1e14f7d7b6 | ||
|
|
5bd4c1ecb6 | ||
|
|
406f3da615 | ||
|
|
302eb082d6 | ||
|
|
16b75653dc | ||
|
|
fc8176a229 | ||
|
|
502c7fb6db | ||
|
|
71f747aec1 | ||
|
|
0ed83cf9f2 | ||
|
|
c37fc01bb1 | ||
|
|
7fae28135e | ||
|
|
82c722ba37 | ||
|
|
aba5567a15 | ||
|
|
d593a04dda | ||
|
|
8fa758f8aa | ||
|
|
2a0d8afe4e | ||
|
|
3e3a11bd0f | ||
|
|
41b2f054f8 | ||
|
|
69c9c70d21 | ||
|
|
243fdf8f7f | ||
|
|
337002f421 | ||
|
|
a7ba6a7421 | ||
|
|
7b3928db9b | ||
|
|
b86770c39f | ||
|
|
f6622104bf | ||
|
|
860739fce2 | ||
|
|
38eb63a7a2 | ||
|
|
f7daf04204 | ||
|
|
2350c59cc8 | ||
|
|
16cdd6bf64 | ||
|
|
e657bcf03a | ||
|
|
d138f64bd6 | ||
|
|
3c37f775fb | ||
|
|
7a283bfaeb | ||
|
|
aebb767cfb | ||
|
|
04b1514452 | ||
|
|
22f9c96a1f | ||
|
|
78b08a0bee | ||
|
|
6fc58a1025 | ||
|
|
c1510a5bea | ||
|
|
7a20432b1b | ||
|
|
3d8be2d2da | ||
|
|
a59e8ff958 | ||
|
|
26077f47af | ||
|
|
118f3c5141 | ||
|
|
22b65a3095 | ||
|
|
05c51a1c05 | ||
|
|
21f95465da | ||
|
|
ab74bdca79 | ||
|
|
69d471aefb | ||
|
|
d620dc0b52 | ||
|
|
d3f975816e | ||
|
|
91ac9178f1 | ||
|
|
ae52d2743e | ||
|
|
a4082a0e54 | ||
|
|
9c8e825289 | ||
|
|
9662452c09 | ||
|
|
0a3051349a | ||
|
|
1c258cb690 | ||
|
|
4ba453f337 | ||
|
|
6960045e2b | ||
|
|
803925f2cf | ||
|
|
97c71ef700 | ||
|
|
6b7752792d | ||
|
|
b7dc2438a7 | ||
|
|
dbd2b9b30a | ||
|
|
9aa3015929 | ||
|
|
09f0c43e7c | ||
|
|
a570191859 | ||
|
|
d7dea30de6 | ||
|
|
8a25500eca | ||
|
|
4d00e8c569 | ||
|
|
02088e0da6 | ||
|
|
f341d0c3a9 | ||
|
|
e27828d248 | ||
|
|
44cf0d0e51 | ||
|
|
6be55685c8 | ||
|
|
29b7321094 | ||
|
|
449b00ed3e | ||
|
|
4c2573702e | ||
|
|
88d4b348d9 | ||
|
|
bf07a9435b | ||
|
|
799b2a381f | ||
|
|
8b4cf14e53 | ||
|
|
515511d5e9 | ||
|
|
aca8cc6fbf | ||
|
|
1bc3834345 | ||
|
|
73e96cdcab | ||
|
|
760e32c5bd | ||
|
|
cf1b167954 | ||
|
|
5ef6c64568 | ||
|
|
7e05e97c95 | ||
|
|
5cd98c5508 | ||
|
|
290f64f552 | ||
|
|
59caa1f300 | ||
|
|
882b5c9b8a | ||
|
|
7ba0c583af | ||
|
|
b275cab13f | ||
|
|
f20c121745 | ||
|
|
25040affc2 | ||
|
|
82e6250250 | ||
|
|
9f2d53a3a2 | ||
|
|
ec4ebbdcfb | ||
|
|
aeeae26d1c | ||
|
|
095d223e70 | ||
|
|
55eed9efd8 | ||
|
|
d092ae9295 | ||
|
|
5457476e4a | ||
|
|
5dce90eafa | ||
|
|
268ea201da | ||
|
|
613b759077 | ||
|
|
fc725cce01 | ||
|
|
95398cd26f | ||
|
|
01e8cf90c6 | ||
|
|
7152bd0ffa | ||
|
|
05861e5340 | ||
|
|
aa853a0f0f | ||
|
|
a47151c638 | ||
|
|
06642bba20 | ||
|
|
f04a460d63 | ||
|
|
7d4ce0daeb | ||
|
|
a2bcd53eaa | ||
|
|
5a47fb64c3 | ||
|
|
c96aa2eda8 | ||
|
|
e30a342813 | ||
|
|
320672c1f9 | ||
|
|
436107f20e | ||
|
|
950e3894b3 | ||
|
|
2300f2bcb0 | ||
|
|
a6d776ca04 | ||
|
|
76e79d6f92 | ||
|
|
9cc1905f87 | ||
|
|
78e24a6fe6 | ||
|
|
f1a353840a | ||
|
|
0f34252f4a | ||
|
|
000a24c63b | ||
|
|
32d4f249d4 | ||
|
|
e71915b4fb | ||
|
|
31b9ba8dde | ||
|
|
83708695af | ||
|
|
bb363db7f8 | ||
|
|
ba6c3b6854 | ||
|
|
200da2b1be | ||
|
|
db652744ef | ||
|
|
9f3d4fb524 | ||
|
|
86b6502342 | ||
|
|
fa671073fa | ||
|
|
4f1e5a72a0 | ||
|
|
bca574119b | ||
|
|
acb8f5f076 | ||
|
|
16ff5c6683 | ||
|
|
67d53c04b7 | ||
|
|
910f78b569 | ||
|
|
fdaf26e95d | ||
|
|
a8854375f5 | ||
|
|
9937e5a17b | ||
|
|
67b0860a9f | ||
|
|
5b90432f7e | ||
|
|
7cd8974b7e | ||
|
|
9c042a5767 | ||
|
|
3db00fa137 | ||
|
|
f6710e2379 | ||
|
|
990dee6a8d | ||
|
|
7bfec0f3c0 | ||
|
|
3ea1a9eee4 | ||
|
|
f6e292fad3 | ||
|
|
1cce7890d8 | ||
|
|
61340cab17 | ||
|
|
4a95dbeddc | ||
|
|
45178111b3 | ||
|
|
eef0f5f0dc | ||
|
|
1e1025f17d | ||
|
|
69407123ba | ||
|
|
096d43a7a6 | ||
|
|
00b67269d6 | ||
|
|
7baf50506b | ||
|
|
40616b864a | ||
|
|
561bbbe294 | ||
|
|
fba7231261 | ||
|
|
b3ac18f173 | ||
|
|
e2a59fccb2 | ||
|
|
a8f26b16c2 | ||
|
|
b7a3999da8 | ||
|
|
a5c8e0b1e2 | ||
|
|
2768e60ce1 | ||
|
|
9075d4a037 | ||
|
|
da35ef695b | ||
|
|
394319e1fc | ||
|
|
0c6e6fdd84 | ||
|
|
39bb82bd9a | ||
|
|
25d7faea7b | ||
|
|
a0c2de60d3 | ||
|
|
e8299fd116 | ||
|
|
4548228238 | ||
|
|
fe1372c962 | ||
|
|
a6fcfa61b5 | ||
|
|
c34e9b3c34 | ||
|
|
ea81eeec57 | ||
|
|
19ae8506ab | ||
|
|
803676d56a | ||
|
|
5975703b13 | ||
|
|
ecd2ce227b | ||
|
|
3f502b6151 | ||
|
|
fb43787317 | ||
|
|
f81bfd9f1c | ||
|
|
24ebb7b379 | ||
|
|
2460f2fcf7 | ||
|
|
401e696590 | ||
|
|
29035199f3 | ||
|
|
b4210d8f61 | ||
|
|
c120af6b1f | ||
|
|
96ea09e44f | ||
|
|
f5a1b1c27d | ||
|
|
5cdfffa521 | ||
|
|
a5245accf4 | ||
|
|
9bc63ccf7e | ||
|
|
2e3ed79753 | ||
|
|
da3b5c2570 | ||
|
|
756b37d4a5 | ||
|
|
36b7d434ad | ||
|
|
b21b308203 | ||
|
|
dab8a36a13 | ||
|
|
152e6f9572 | ||
|
|
f8fbf370bc | ||
|
|
61291c77d7 | ||
|
|
b90df8b254 | ||
|
|
4dbc0dd47f | ||
|
|
9d3db1b103 | ||
|
|
b8c8b9e605 | ||
|
|
d7260665d6 | ||
|
|
b96c95066c | ||
|
|
3d352c6fcd | ||
|
|
874572f7bb | ||
|
|
8f0d7d0805 | ||
|
|
65f8d2629a | ||
|
|
c0ca2249a5 | ||
|
|
efe903bc73 | ||
|
|
fd20e0725b | ||
|
|
6c8f094bbe | ||
|
|
50b76d59f7 | ||
|
|
4f76b42bb5 | ||
|
|
d593ab38ad | ||
|
|
a17f974357 | ||
|
|
40dee9958b | ||
|
|
575bdda768 | ||
|
|
9b116929ad | ||
|
|
2e8fa61a5a | ||
|
|
cd93eb9098 | ||
|
|
4c765d86ee | ||
|
|
fa8aaced55 | ||
|
|
1b02ab5f7f | ||
|
|
0e609cc528 | ||
|
|
5ec4c74b0b | ||
|
|
4d7006950a | ||
|
|
e49a69895a | ||
|
|
27f2b9c219 | ||
|
|
db820fbb0f | ||
|
|
ad4e9c74e0 | ||
|
|
4797446f7c | ||
|
|
0ffcde4fbb | ||
|
|
f555e1143f | ||
|
|
bc3fd4542b | ||
|
|
d3fac14586 | ||
|
|
d0425a140a | ||
|
|
64ec0c317e | ||
|
|
5f694f82af | ||
|
|
590122f25a | ||
|
|
9b670b9ea7 | ||
|
|
65e836cba1 | ||
|
|
c634f61f2a | ||
|
|
776e78c459 | ||
|
|
a03235851c | ||
|
|
d2f843f92c | ||
|
|
e9c69673ad | ||
|
|
a453afa29a | ||
|
|
cee669c276 | ||
|
|
2e0c1b0086 | ||
|
|
7686c86792 | ||
|
|
2e0f0211d1 | ||
|
|
4f8d745305 | ||
|
|
9788c6849e | ||
|
|
48dfbac37a | ||
|
|
e4eccce811 | ||
|
|
097c2fea42 | ||
|
|
5a5b171a68 | ||
|
|
343d6866c4 | ||
|
|
2ad144c739 | ||
|
|
983ad61d78 | ||
|
|
27e87143e1 | ||
|
|
d0b802e09b | ||
|
|
8c67631efb | ||
|
|
18df114b70 | ||
|
|
c51bf739cf | ||
|
|
43a0a7db4f | ||
|
|
bbcfe7edf4 | ||
|
|
a11578a863 | ||
|
|
b546304d5d | ||
|
|
d7774c0dc0 | ||
|
|
bd80144c7b | ||
|
|
af37928283 | ||
|
|
6a3df43017 | ||
|
|
7bfbe83d87 | ||
|
|
a871569867 | ||
|
|
65b071eb86 | ||
|
|
0e99d4fa80 | ||
|
|
8f00c3c274 | ||
|
|
4fad53007f | ||
|
|
e7435964a2 | ||
|
|
8ea15468b4 | ||
|
|
9025bef687 | ||
|
|
ffc44bb089 | ||
|
|
6c968489eb | ||
|
|
2fc1b66a79 | ||
|
|
bd99d0451d | ||
|
|
d62e47cd2e | ||
|
|
ab23fedd0c | ||
|
|
43a603c1cc | ||
|
|
9b5b541c82 | ||
|
|
119bac527f | ||
|
|
e9bc6a2915 | ||
|
|
2979338f8a | ||
|
|
830f633a6e | ||
|
|
0d51d12e43 | ||
|
|
2d47989616 | ||
|
|
f259b5e825 | ||
|
|
3800b33c1a | ||
|
|
dfe0eff095 | ||
|
|
8cdec40a03 | ||
|
|
6169234300 | ||
|
|
3ff2d82ecf | ||
|
|
3ef4c09f71 | ||
|
|
79bd7ac090 | ||
|
|
6e648f14f4 | ||
|
|
c3d8254324 | ||
|
|
15095640eb | ||
|
|
6070419761 | ||
|
|
db2f48ad09 | ||
|
|
cfe5206252 | ||
|
|
975f679148 | ||
|
|
b571a3d58d | ||
|
|
5090d4b3a0 | ||
|
|
799b00211d | ||
|
|
afe8afc41f | ||
|
|
090e7c0ecb | ||
|
|
e557b78394 | ||
|
|
c53f961690 | ||
|
|
9e6b51fac9 | ||
|
|
a6f98158a7 | ||
|
|
ca040bdf9a | ||
|
|
f95cf6454d | ||
|
|
827c6adc03 | ||
|
|
59d9ece06b | ||
|
|
1dd1b09e5f | ||
|
|
58296ecaf7 | ||
|
|
3b0674320f | ||
|
|
a8b2b4f962 | ||
|
|
6fc32b6800 | ||
|
|
1e20d43c2a | ||
|
|
52814bcbd0 | ||
|
|
74fccaaab5 | ||
|
|
6813a06455 | ||
|
|
e423cfee35 | ||
|
|
7316a00e9c | ||
|
|
54299d766a | ||
|
|
f2a7b4b349 | ||
|
|
150718ad6f | ||
|
|
0904ec151c | ||
|
|
dff6e0832c | ||
|
|
e983c03232 | ||
|
|
d1c54608f7 | ||
|
|
24b6c88935 | ||
|
|
6397e56c06 | ||
|
|
9785111857 | ||
|
|
522ffb08f0 | ||
|
|
22129e3ec7 | ||
|
|
4431864770 | ||
|
|
23a57f7876 | ||
|
|
05b75aa44c | ||
|
|
e35a1ca231 | ||
|
|
1cc6c2b9ca | ||
|
|
8c092c7453 | ||
|
|
6631fce15f | ||
|
|
7071142aad | ||
|
|
34586bca5a | ||
|
|
516638a6d7 | ||
|
|
d4c39a2ad9 | ||
|
|
d6288c175e | ||
|
|
08b785083a | ||
|
|
a7818f0f64 | ||
|
|
52642aa11a | ||
|
|
27c886f6b9 | ||
|
|
85eb5a7496 | ||
|
|
91c242ac04 | ||
|
|
8ff6c147f2 | ||
|
|
8b4bb5a078 | ||
|
|
9d260f9b0e | ||
|
|
59cd48f3de | ||
|
|
b11db20742 | ||
|
|
f186aa6896 | ||
|
|
2bedf000a8 | ||
|
|
3d6f4544f1 | ||
|
|
13deac9b58 | ||
|
|
21c60ef7ce | ||
|
|
83adbb2979 | ||
|
|
c614b679e1 | ||
|
|
10bcc69c80 | ||
|
|
9eb4368d6f | ||
|
|
783fd4b475 | ||
|
|
00efab8ad2 | ||
|
|
d73b3745bf | ||
|
|
ccd44c0cb2 | ||
|
|
9a0acca849 | ||
|
|
95f9658a7e | ||
|
|
0fa24ce313 | ||
|
|
28ad466aa8 | ||
|
|
7e9fc0f20b | ||
|
|
7f5689835b | ||
|
|
478e0a53d0 | ||
|
|
588cad8d91 | ||
|
|
1d3ab8d6bb | ||
|
|
e086aa1660 | ||
|
|
188a15a948 | ||
|
|
874660f52e | ||
|
|
29bd46d68d | ||
|
|
cb80e0ef51 | ||
|
|
ccef53a3d3 | ||
|
|
d201803259 | ||
|
|
74b206dc77 | ||
|
|
42cda2d2e0 | ||
|
|
c386b704b5 | ||
|
|
84be00b29f | ||
|
|
d064b589ae | ||
|
|
90edd12e43 | ||
|
|
c71bf3ccbe | ||
|
|
724b4de07e | ||
|
|
444b0a928d | ||
|
|
ec8fcbc02f | ||
|
|
68e2cd67d1 | ||
|
|
c21e1aba35 | ||
|
|
ec7f38d157 | ||
|
|
5b38483981 | ||
|
|
46312a2d15 | ||
|
|
8a240f7c46 | ||
|
|
17ca061cda | ||
|
|
4da902b46c | ||
|
|
7b39268171 | ||
|
|
0343569cdc | ||
|
|
32a804e2ea | ||
|
|
7ce078eb16 | ||
|
|
f9dda21088 | ||
|
|
00c5ae4a42 | ||
|
|
d73d8333a1 | ||
|
|
9c720fd6b7 | ||
|
|
7228235ce3 | ||
|
|
5684a1477e | ||
|
|
347dd73269 | ||
|
|
a14850458d | ||
|
|
e249e3cfb6 | ||
|
|
d1c0978ee5 | ||
|
|
e3226d3511 | ||
|
|
ae7c416f16 | ||
|
|
1456fa0f75 | ||
|
|
d6acd07d5c | ||
|
|
d8149e9eb0 | ||
|
|
d6557e21a0 | ||
|
|
3bccef8d22 | ||
|
|
a27e8316fe | ||
|
|
b419948c8d | ||
|
|
211555639d | ||
|
|
46125abdeb | ||
|
|
69e4e7cc49 | ||
|
|
fe9dedb9ad | ||
|
|
47e6a96800 | ||
|
|
f42fb51952 | ||
|
|
1aea1b699a | ||
|
|
e769ba58cc | ||
|
|
f815eec2c0 | ||
|
|
de9be8b481 | ||
|
|
7454b8f2f6 | ||
|
|
b4c7dbe478 | ||
|
|
e14727dcc3 | ||
|
|
ac4e4e405b | ||
|
|
898216ac9f | ||
|
|
c42e3a3f47 | ||
|
|
cec9166956 | ||
|
|
675c66ff9d | ||
|
|
962a110b16 | ||
|
|
405410b8c8 | ||
|
|
32e014af06 | ||
|
|
0af86bbb9d | ||
|
|
a31dc3a102 | ||
|
|
7b212ea7fd | ||
|
|
b3f3944495 | ||
|
|
58a05e2ee7 | ||
|
|
3146ffb8e1 | ||
|
|
b815ce9db4 | ||
|
|
b14aa16a23 | ||
|
|
4397d85727 | ||
|
|
98832c4914 | ||
|
|
720269b118 | ||
|
|
c9bd13213b | ||
|
|
5fdddaeede | ||
|
|
8570539aab | ||
|
|
f4c6738793 | ||
|
|
e018ee98d3 | ||
|
|
95aabd561b | ||
|
|
a1b295c2c9 | ||
|
|
bc7aff3f11 | ||
|
|
dc249c1ec5 | ||
|
|
660228fb0e | ||
|
|
57c1f3e067 | ||
|
|
6ed9ae4bb9 | ||
|
|
752f754bb2 | ||
|
|
44a547341d | ||
|
|
c3f2c693a2 | ||
|
|
918217f6d2 | ||
|
|
bbdc432a20 | ||
|
|
5ba9562b17 | ||
|
|
fabfdcd178 | ||
|
|
33fac1c5af | ||
|
|
d60b87d98e | ||
|
|
c7881dec35 | ||
|
|
df0178e2de | ||
|
|
aaa60d261d | ||
|
|
88ab4b6f52 | ||
|
|
f9d3dbfa61 | ||
|
|
41d05dd922 | ||
|
|
82c2448321 | ||
|
|
a67b546a02 | ||
|
|
842d318277 | ||
|
|
251706d646 | ||
|
|
cbaa635a89 | ||
|
|
0a4bc6576a | ||
|
|
9a266ca52e | ||
|
|
4b6fc55056 | ||
|
|
c9bdb6ef04 | ||
|
|
bc52c0141a | ||
|
|
b2145b6838 | ||
|
|
74337fb65a | ||
|
|
4ffb7ea64a | ||
|
|
3d7e8c6c95 | ||
|
|
50de4d78e5 | ||
|
|
14358a8c37 | ||
|
|
9afa5febc2 | ||
|
|
70e09246ee | ||
|
|
4e8e3b9774 | ||
|
|
32129634ee |
No files matched your search
@@ -1,4 +0,0 @@
|
||||
*.pbxuser
|
||||
.DS_Store
|
||||
*.perspective*
|
||||
.svn
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
# Xcode
|
||||
build/*
|
||||
*.pbxuser
|
||||
!default.pbxuser
|
||||
*.mode1v3
|
||||
!default.mode1v3
|
||||
*.mode2v3
|
||||
!default.mode2v3
|
||||
*.perspectivev3
|
||||
!default.perspectivev3
|
||||
*.xcworkspace
|
||||
!default.xcworkspace
|
||||
xcuserdata/
|
||||
profile
|
||||
*.moved-aside
|
||||
|
||||
## Ignore incredibly annoying .DS_Store files
|
||||
.DS_Store
|
||||
@@ -0,0 +1,8 @@
|
||||
// BinaryDelta tool only
|
||||
|
||||
PRODUCT_NAME = BinaryDelta
|
||||
GCC_PREFIX_HEADER =
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=i386] = 10.5
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=ppc64] = 10.5
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=ppc] = 10.5
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=x86_64] = 10.5
|
||||
@@ -0,0 +1,5 @@
|
||||
#include "ConfigCommon.xcconfig"
|
||||
#include "ConfigCommonDebug.xcconfig"
|
||||
#include "ConfigBinaryDelta.xcconfig"
|
||||
|
||||
OTHER_CFLAGS = -DDEBUG
|
||||
@@ -0,0 +1,3 @@
|
||||
#include "ConfigCommon.xcconfig"
|
||||
#include "ConfigCommonRelease.xcconfig"
|
||||
#include "ConfigBinaryDelta.xcconfig"
|
||||
@@ -3,17 +3,20 @@
|
||||
PREBINDING = NO
|
||||
ZERO_LINK = NO
|
||||
CURRENT_PROJECT_VERSION = 1.5
|
||||
SDKROOT = $(DEVELOPER_SDK_DIR)/MacOSX10.5.sdk
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=ppc] = 10.3
|
||||
SDKROOT = macosx10.8
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=ppc] = 10.4
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=ppc64] = 10.5
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=i386] = 10.4
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=x86_64] = 10.5
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=x86_64] = 10.7
|
||||
GCC_C_LANGUAGE_STANDARD = c99
|
||||
GCC_ENABLE_OBJC_EXCEPTIONS = YES
|
||||
GCC_DEBUGGING_SYMBOLS = full
|
||||
GCC_PRECOMPILE_PREFIX_HEADER = YES
|
||||
GCC_PREFIX_HEADER = $(SDKROOT)/System/Library/Frameworks/Cocoa.framework/Headers/Cocoa.h
|
||||
GCC_FAST_OBJC_DISPATCH = YES
|
||||
GCC_FAST_OBJC_DISPATCH[arch=ppc] = NO // requires 10.4
|
||||
GCC_ENABLE_PASCAL_STRINGS = NO
|
||||
GCC_VERSION = com.apple.compilers.llvm.clang.1_0
|
||||
CLANG_LINK_OBJC_RUNTIME = NO
|
||||
|
||||
// Enable warnings
|
||||
GCC_WARN_CHECK_SWITCH_STATEMENTS = YES
|
||||
@@ -35,4 +38,15 @@ GCC_WARN_UNKNOWN_PRAGMAS = YES
|
||||
GCC_WARN_UNUSED_VARIABLE = YES
|
||||
GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = YES
|
||||
GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = YES
|
||||
WARNING_CFLAGS = -Wall
|
||||
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES
|
||||
GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES
|
||||
GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = YES
|
||||
GCC_WARN_UNUSED_FUNCTION = YES
|
||||
GCC_WARN_UNUSED_LABEL = YES
|
||||
GCC_WARN_UNUSED_VALUE = YES
|
||||
GCC_WARN_UNUSED_PARAMETER = YES
|
||||
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES
|
||||
|
||||
COMMON_WARNING_FLAGS = -Wall -Wno-unused-parameter -Wundef -Wendif-labels -Wpointer-arith -Wcast-align -Wwrite-strings -Wmissing-format-attribute -Wpacked -Wredundant-decls -Winline -Wdisabled-optimization -Winvalid-pch
|
||||
WARNING_CFLAGS = $(COMMON_WARNING_FLAGS)
|
||||
@@ -3,6 +3,9 @@
|
||||
GCC_OPTIMIZATION_LEVEL = 0
|
||||
DEBUG_INFORMATION_FORMAT = dwarf
|
||||
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
|
||||
SPARKLE_EXTRA_DEBUG = -DDEBUG -fstack-protector -D_FORTIFY_SOURCE=2
|
||||
SPARKLE_EXTRA_DEBUG_10_5_ONLY = -fstack-protector -D_FORTIFY_SOURCE=2
|
||||
SPARKLE_EXTRA_DEBUG = -DDEBUG
|
||||
OTHER_CFLAGS = $(SPARKLE_EXTRA_DEBUG)
|
||||
ARCHS = $(NATIVE_ARCH_ACTUAL)
|
||||
CODE_SIGN_IDENTITY = Mac Developer
|
||||
|
||||
// Add $(SPARKLE_EXTRA_DEBUG_10_5_ONLY) to SPARKLE_EXTRA_DEBUG if your deployment is 10.5 or greater.
|
||||
@@ -0,0 +1,4 @@
|
||||
// Common
|
||||
|
||||
ARCHS = x86_64
|
||||
VALID_ARCHS = x86_64
|
||||
@@ -0,0 +1,4 @@
|
||||
// Common
|
||||
|
||||
ARCHS = ppc i386 x86_64
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
GCC_OPTIMIZATION_LEVEL = s
|
||||
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
|
||||
GCC_GENERATE_DEBUGGING_SYMBOLS = NO
|
||||
DEAD_CODE_STRIPPING = YES
|
||||
GCC_TREAT_WARNINGS_AS_ERRORS = YES
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES
|
||||
ARCHS = ppc i386 x86_64
|
||||
WARNING_CFLAGS = $(COMMON_WARNING_FLAGS) -Wno-deprecated-declarations
|
||||
CODE_SIGN_IDENTITY = Developer ID Application
|
||||
@@ -1,10 +1,10 @@
|
||||
// Framework only
|
||||
|
||||
INSTALL_PATH = @executable_path/../Frameworks
|
||||
DYLIB_COMPATIBILITY_VERSION = 1.5
|
||||
DYLIB_CURRENT_VERSION = 1.5
|
||||
INSTALL_PATH = @loader_path/../Frameworks
|
||||
DYLIB_COMPATIBILITY_VERSION = 2.0
|
||||
DYLIB_CURRENT_VERSION = 2.0
|
||||
PRODUCT_NAME = Sparkle
|
||||
WRAPPER_EXTENSION = framework
|
||||
OTHER_LDFLAGS = -lcrypto
|
||||
FRAMEWORK_VERSION = A
|
||||
INFOPLIST_FILE = Info.plist
|
||||
GCC_PREFIX_HEADER = Sparkle.pch
|
||||
@@ -2,4 +2,4 @@
|
||||
#include "ConfigCommonDebug.xcconfig"
|
||||
#include "ConfigFramework.xcconfig"
|
||||
|
||||
OTHER_CFLAGS = -fsingle-precision-constant -DDEBUG
|
||||
OTHER_CFLAGS = -DDEBUG
|
||||
@@ -1,3 +1,9 @@
|
||||
#include "ConfigCommon.xcconfig"
|
||||
#include "ConfigCommonRelease.xcconfig"
|
||||
#include "ConfigFramework.xcconfig"
|
||||
|
||||
STRIP_INSTALLED_PRODUCT = YES
|
||||
DEPLOYMENT_POSTPROCESSING = YES
|
||||
STRIPFLAGS = -u -r
|
||||
STRIP_STYLE = non-global
|
||||
SEPARATE_STRIP = YES
|
||||
@@ -1,3 +1,4 @@
|
||||
// Relaunch Tool only
|
||||
|
||||
PRODUCT_NAME = relaunch
|
||||
PRODUCT_NAME = finish_installation
|
||||
SKIP_INSTALL = YES
|
||||
@@ -2,4 +2,4 @@
|
||||
#include "ConfigCommonDebug.xcconfig"
|
||||
#include "ConfigRelaunch.xcconfig"
|
||||
|
||||
OTHER_CFLAGS = -fsingle-precision-constant -DDEBUG
|
||||
OTHER_CFLAGS = -DDEBUG
|
||||
@@ -0,0 +1,10 @@
|
||||
// Sandbox Service only
|
||||
|
||||
WRAPPER_EXTENSION = xpc
|
||||
MACH_O_TYPE = mh_execute
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.7
|
||||
MACOSX_DEPLOYMENT_TARGET[arch=x86_64] = 10.7
|
||||
|
||||
GCC_WARN_SHADOW = NO
|
||||
GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO
|
||||
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = NO
|
||||
@@ -0,0 +1,5 @@
|
||||
#include "ConfigCommon.xcconfig"
|
||||
#include "ConfigCommonDebug.xcconfig"
|
||||
#include "ConfigService.xcconfig"
|
||||
|
||||
OTHER_CFLAGS = -DDEBUG
|
||||
@@ -0,0 +1,3 @@
|
||||
#include "ConfigCommon.xcconfig"
|
||||
#include "ConfigCommonRelease.xcconfig"
|
||||
#include "ConfigService.xcconfig"
|
||||
@@ -2,4 +2,4 @@
|
||||
#include "ConfigCommonDebug.xcconfig"
|
||||
#include "ConfigTestApp.xcconfig"
|
||||
|
||||
OTHER_CFLAGS = -fsingle-precision-constant -DDEBUG
|
||||
OTHER_CFLAGS = -DDEBUG
|
||||
@@ -0,0 +1,3 @@
|
||||
#include "ConfigTestAppRelease.xcconfig"
|
||||
|
||||
GCC_ENABLE_OBJC_GC = required
|
||||
@@ -0,0 +1,11 @@
|
||||
// Unit Test only
|
||||
|
||||
INFOPLIST_FILE = Tests/Sparkle Unit Tests-Info.plist
|
||||
OTHER_LDFLAGS = -framework Cocoa -framework SenTestingKit
|
||||
PRODUCT_NAME = Sparkle Unit Tests
|
||||
WRAPPER_EXTENSION = octest
|
||||
FRAMEWORK_SEARCH_PATHS = $(DEVELOPER_LIBRARY_DIR)/Frameworks
|
||||
GCC_PREFIX_HEADER = $(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h
|
||||
GCC_PRECOMPILE_PREFIX_HEADER = YES
|
||||
SDKROOT = macosx10.7
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.7
|
||||
@@ -0,0 +1,3 @@
|
||||
#include "ConfigCommon.xcconfig"
|
||||
#include "ConfigCommonDebug.xcconfig"
|
||||
#include "ConfigUnitTest.xcconfig"
|
||||
@@ -0,0 +1,3 @@
|
||||
#include "ConfigCommon.xcconfig"
|
||||
#include "ConfigCommonRelease.xcconfig"
|
||||
#include "ConfigUnitTest.xcconfig"
|
||||
@@ -0,0 +1,3 @@
|
||||
#include "ConfigUnitTestRelease.xcconfig"
|
||||
|
||||
GCC_ENABLE_OBJC_GC = required
|
||||
@@ -0,0 +1,31 @@
|
||||
<?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>CFBundleDevelopmentRegion</key>
|
||||
<string>English</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>XPC!</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>XPCService</key>
|
||||
<dict>
|
||||
<key>ServiceType</key>
|
||||
<string>Application</string>
|
||||
<key>JoinExistingSession</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,4 @@
|
||||
//
|
||||
// Prefix header for all source files of the 'Downloading XPC Service' target in the 'Downloading XPC Service' project
|
||||
//
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//
|
||||
// SUDSDownloader.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Dmytro Tretiakov on 8/1/13.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#define DEBUG_LOGGING_ENABLED defined(DEBUG) && 1
|
||||
|
||||
@class SUDSDownloader;
|
||||
|
||||
typedef void (^SUDSDownloadDidBegin)(SUDSDownloader *downloader);
|
||||
typedef void (^SUDSDownloadDidFinish)(SUDSDownloader *downloader);
|
||||
typedef void (^SUDSDownloadDidFail)(SUDSDownloader *downloader, NSError *error);
|
||||
typedef void (^SUDSDownloadDidReceiveResponse)(SUDSDownloader *downloader, NSURLResponse *response);
|
||||
typedef void (^SUDSDownloadDidReceiveData)(SUDSDownloader *downloader, NSUInteger dataLength);
|
||||
typedef void (^SUDSDownloadDidCreateDestination)(SUDSDownloader *downloader, NSString *destinationPath);
|
||||
typedef BOOL (^SUDSDownloadShouldDecodeSourceData)(SUDSDownloader *downloader, NSString *MIMEType);
|
||||
|
||||
typedef struct SUDSDownloaderCallBacks
|
||||
{
|
||||
SUDSDownloadDidBegin downloadDidBegin;
|
||||
SUDSDownloadDidFinish downloadDidFinish;
|
||||
SUDSDownloadDidFail downloadDidFail;
|
||||
|
||||
SUDSDownloadDidReceiveResponse downloadDidReceiveResponse;
|
||||
SUDSDownloadDidReceiveData downloadDidReceiveData;
|
||||
SUDSDownloadDidCreateDestination downloadDidCreateDestination;
|
||||
|
||||
SUDSDownloadShouldDecodeSourceData downloadShouldDecodeSourceData;
|
||||
} SUDSDownloaderCallBacks;
|
||||
|
||||
FOUNDATION_EXTERN SUDSDownloaderCallBacks SUDSCopyDownloaderCallBacks(SUDSDownloaderCallBacks callBacks);
|
||||
FOUNDATION_EXTERN void SUDSReleaseDownloaderCallBacks(SUDSDownloaderCallBacks callBacks);
|
||||
|
||||
@interface SUDSDownloader : NSObject <NSURLDownloadDelegate>
|
||||
{
|
||||
@private
|
||||
NSURLRequest *_request;
|
||||
NSString *_destFilePath;
|
||||
SUDSDownloaderCallBacks _callBacks;
|
||||
|
||||
NSURLDownload *_download;
|
||||
}
|
||||
|
||||
- (id)initWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath;
|
||||
+ (id)downloaderWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath;
|
||||
|
||||
- (NSURLRequest *)request;
|
||||
- (NSString *)destinationPath;
|
||||
- (void)setCallBacks:(SUDSDownloaderCallBacks)callBacks;
|
||||
|
||||
- (void)startDownload;
|
||||
- (void)stopDownload;
|
||||
- (BOOL)isInProgress;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,210 @@
|
||||
//
|
||||
// SUDSDownloader.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Dmytro Tretiakov on 8/1/13.
|
||||
//
|
||||
//
|
||||
|
||||
#import "SUDSDownloader.h"
|
||||
|
||||
SUDSDownloaderCallBacks SUDSCopyDownloaderCallBacks(SUDSDownloaderCallBacks callBacks)
|
||||
{
|
||||
SUDSDownloaderCallBacks callBacksCopy = {0};
|
||||
|
||||
if (callBacks.downloadDidBegin)
|
||||
callBacksCopy.downloadDidBegin = Block_copy(callBacks.downloadDidBegin);
|
||||
if (callBacks.downloadDidFinish)
|
||||
callBacksCopy.downloadDidFinish = Block_copy(callBacks.downloadDidFinish);
|
||||
if (callBacks.downloadDidFail)
|
||||
callBacksCopy.downloadDidFail = Block_copy(callBacks.downloadDidFail);
|
||||
if (callBacks.downloadDidReceiveData)
|
||||
callBacksCopy.downloadDidReceiveData = Block_copy(callBacks.downloadDidReceiveData);
|
||||
if (callBacks.downloadDidCreateDestination)
|
||||
callBacksCopy.downloadDidCreateDestination = Block_copy(callBacks.downloadDidCreateDestination);
|
||||
if (callBacks.downloadDidReceiveResponse)
|
||||
callBacksCopy.downloadDidReceiveResponse = Block_copy(callBacks.downloadDidReceiveResponse);
|
||||
if (callBacks.downloadShouldDecodeSourceData)
|
||||
callBacksCopy.downloadShouldDecodeSourceData = Block_copy(callBacks.downloadShouldDecodeSourceData);
|
||||
|
||||
return callBacksCopy;
|
||||
}
|
||||
|
||||
void SUDSReleaseDownloaderCallBacks(SUDSDownloaderCallBacks callBacks)
|
||||
{
|
||||
if (callBacks.downloadDidBegin)
|
||||
Block_release(callBacks.downloadDidBegin);
|
||||
if (callBacks.downloadDidFinish)
|
||||
Block_release(callBacks.downloadDidFinish);
|
||||
if (callBacks.downloadDidFail)
|
||||
Block_release(callBacks.downloadDidFail);
|
||||
if (callBacks.downloadDidReceiveData)
|
||||
Block_release(callBacks.downloadDidReceiveData);
|
||||
if (callBacks.downloadDidCreateDestination)
|
||||
Block_release(callBacks.downloadDidCreateDestination);
|
||||
if (callBacks.downloadDidReceiveResponse)
|
||||
Block_release(callBacks.downloadDidReceiveResponse);
|
||||
if (callBacks.downloadShouldDecodeSourceData)
|
||||
Block_release(callBacks.downloadShouldDecodeSourceData);
|
||||
}
|
||||
|
||||
@implementation SUDSDownloader
|
||||
|
||||
- (id)initWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil)
|
||||
{
|
||||
_request = [request retain];
|
||||
_destFilePath = [filePath copy];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (id)downloaderWithURLRequest:(NSURLRequest *)request destinationPath:(NSString *)filePath
|
||||
{
|
||||
return [[[[self class] alloc] initWithURLRequest:request destinationPath:filePath] autorelease];
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[self stopDownload];
|
||||
|
||||
[_request release];
|
||||
[_destFilePath release];
|
||||
SUDSReleaseDownloaderCallBacks(_callBacks);
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (NSURLRequest *)request
|
||||
{
|
||||
return _request;
|
||||
}
|
||||
|
||||
- (NSString *)destinationPath
|
||||
{
|
||||
return _destFilePath;
|
||||
}
|
||||
|
||||
- (void)setCallBacks:(SUDSDownloaderCallBacks)callBacks
|
||||
{
|
||||
SUDSDownloaderCallBacks oldCallBacks = _callBacks;
|
||||
_callBacks = SUDSCopyDownloaderCallBacks(callBacks);
|
||||
SUDSReleaseDownloaderCallBacks(oldCallBacks);
|
||||
}
|
||||
|
||||
- (void)startDownload
|
||||
{
|
||||
[self stopDownload];
|
||||
|
||||
// to ensure that parent folder exists
|
||||
[[NSFileManager defaultManager] createDirectoryAtPath:[_destFilePath stringByDeletingLastPathComponent]
|
||||
withIntermediateDirectories:YES
|
||||
attributes:nil
|
||||
error:NULL];
|
||||
NSURLDownload *urlDownload = [[NSURLDownload alloc] initWithRequest:_request delegate:self];
|
||||
@synchronized (self)
|
||||
{
|
||||
_download = urlDownload;
|
||||
}
|
||||
|
||||
[urlDownload setDestination:_destFilePath allowOverwrite:YES];
|
||||
}
|
||||
|
||||
- (void)stopDownload
|
||||
{
|
||||
@synchronized (self)
|
||||
{
|
||||
[_download cancel];
|
||||
[_download release];
|
||||
_download = nil;
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)isInProgress
|
||||
{
|
||||
BOOL result = YES;
|
||||
@synchronized (self)
|
||||
{
|
||||
result = _download != nil;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)downloadDidBegin:(NSURLDownload *)download
|
||||
{
|
||||
#if DEBUG_LOGGING_ENABLED
|
||||
NSLog(@"XPC Downloader did begin process.");
|
||||
#endif
|
||||
if (_callBacks.downloadDidBegin)
|
||||
_callBacks.downloadDidBegin(self);
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response
|
||||
{
|
||||
#if DEBUG_LOGGING_ENABLED
|
||||
NSLog(@"XPC Downloader did receive response: %@", [response description]);
|
||||
#endif
|
||||
if (_callBacks.downloadDidReceiveResponse)
|
||||
_callBacks.downloadDidReceiveResponse(self, response);
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path
|
||||
{
|
||||
#if DEBUG_LOGGING_ENABLED
|
||||
NSLog(@"XPC Downloader did create destination: %@", path);
|
||||
#endif
|
||||
if (_callBacks.downloadDidCreateDestination)
|
||||
_callBacks.downloadDidCreateDestination(self, path);
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(NSUInteger)length
|
||||
{
|
||||
#if DEBUG_LOGGING_ENABLED
|
||||
NSLog(@"XPC Downloader did receive data of length %ld bytes", (unsigned long)length);
|
||||
#endif
|
||||
if (_callBacks.downloadDidReceiveData)
|
||||
_callBacks.downloadDidReceiveData(self, length);
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
|
||||
{
|
||||
#if DEBUG_LOGGING_ENABLED
|
||||
NSLog(@"XPC Downloader did fail: %@", [error description]);
|
||||
#endif
|
||||
if (_callBacks.downloadDidFail)
|
||||
_callBacks.downloadDidFail(self, error);
|
||||
|
||||
[self stopDownload];
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish:(NSURLDownload *)download
|
||||
{
|
||||
#if DEBUG_LOGGING_ENABLED
|
||||
NSLog(@"XPC Downloader did finish");
|
||||
#endif
|
||||
if (_callBacks.downloadDidFinish)
|
||||
_callBacks.downloadDidFinish(self);
|
||||
|
||||
[self stopDownload];
|
||||
}
|
||||
|
||||
- (BOOL)download:(NSURLDownload *)download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
|
||||
{
|
||||
BOOL shouldDecode = NO;
|
||||
|
||||
#if DEBUG_LOGGING_ENABLED
|
||||
NSLog(@"XPC Downloader wants decode source data of MIME type: %@", encodingType);
|
||||
#endif
|
||||
if (_callBacks.downloadShouldDecodeSourceData)
|
||||
shouldDecode = _callBacks.downloadShouldDecodeSourceData(self, encodingType);
|
||||
|
||||
return shouldDecode;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,29 @@
|
||||
//
|
||||
// SUDownloadServiceConstants.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Dmytro Tretiakov on 7/29/13.
|
||||
//
|
||||
//
|
||||
|
||||
#ifndef Sparkle_SUDownloadServiceConstants_h
|
||||
#define Sparkle_SUDownloadServiceConstants_h
|
||||
|
||||
const char * SUDownloadServiceURLRequestDataKey = "request_data"; // data of archived NSURLRequest
|
||||
const char * SUDownloadServiceDelegateConnectionKey = "connection"; // xpc_connection_t
|
||||
const char * SUDownloadServiceFilePathKey = "file_path"; // c-string
|
||||
|
||||
const char * SUDownloadServiceReceivedDataLengthKey = "received_data_length"; // int64_t
|
||||
const char * SUDownloadServiceReceivedResponseDataKey = "received_response_data"; // data of archived NSURLResponse
|
||||
const char * SUDownloadServiceCreatedDestinationPathKey = "created_destination_path"; // c-string
|
||||
const char * SUDownloadServiceDidBeginDownloadingKey = "did_begin_downloading"; // bool 1
|
||||
const char * SUDownloadServiceDidFinishDownloadingKey = "did_finish_downloading"; // bool 1
|
||||
const char * SUDownloadServiceReceivedFailErrorKey = "received_fail_error"; // data of archived NSError
|
||||
const char * SUDownloadServiceMIMETypeToDecodeKey = "MIME_type_to_decode"; // c-string
|
||||
const char * SUDownloadServiceShouldDecodeMIMETypeKey = "should_decode_MIME_type"; // bool
|
||||
|
||||
const char * SUDownloadServiceErrorCodeKey = "errcode"; // int64_t
|
||||
const char * SUDownloadServiceErrorMessageKey = "errmsg"; // c-string
|
||||
const char * SUDownloadServiceErrorDomainKey = "errdomain"; // c-string
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,36 @@
|
||||
//
|
||||
// SUXPCURLDownload.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Erik Aderstedt on 2012-08-09.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface SUXPCURLDownload : NSObject
|
||||
{
|
||||
@private
|
||||
id <NSURLDownloadDelegate> _delegate; // weak ref
|
||||
xpc_connection_t _connection;
|
||||
xpc_connection_t _delegateConnection;
|
||||
NSURLRequest *_request;
|
||||
NSThread *_startedThread; // weak ref
|
||||
BOOL _isDownloading;
|
||||
|
||||
BOOL _allowOverwrite;
|
||||
NSString *_destination;
|
||||
NSString *_connectionDestination;
|
||||
NSError *_downloadError;
|
||||
}
|
||||
|
||||
- (id <NSURLDownloadDelegate>)delegate;
|
||||
- (void)setDelegate:(id <NSURLDownloadDelegate>)delegate;
|
||||
|
||||
- (id)initWithRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate;
|
||||
- (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite;
|
||||
|
||||
// Delegate methods for this method will be called from another thread.
|
||||
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,448 @@
|
||||
//
|
||||
// SUXPCURLDownload.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Erik Aderstedt on 2012-08-09.
|
||||
//
|
||||
//
|
||||
|
||||
#import "SUXPCURLDownload.h"
|
||||
#import "SUDownloadServiceConstants.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SULog.h"
|
||||
|
||||
static NSString * const kSUFetchFolderName = @"fetch.XXXXXXXX";
|
||||
|
||||
@interface SUXPCURLDownload (Private)
|
||||
|
||||
- (void)performBlock:(void (^)(void))block onThread:(NSThread *)thread synchronous:(BOOL)flag;
|
||||
- (void)fireBlock:(void (^)(void))block;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUXPCURLDownload
|
||||
|
||||
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate
|
||||
{
|
||||
__block SUXPCURLDownload *download = nil;
|
||||
|
||||
static const char *sSynchronousDownloadQueueName = "com.devmate.SynchronousXPCDownloadQueue";
|
||||
dispatch_queue_t queue = dispatch_queue_create(sSynchronousDownloadQueueName, NULL);
|
||||
dispatch_sync(queue, ^{
|
||||
download = [[SUXPCURLDownload alloc] initWithRequest:request delegate:delegate];
|
||||
});
|
||||
|
||||
while (download && download->_isDownloading)
|
||||
{
|
||||
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
|
||||
}
|
||||
|
||||
NSData *downloadData = (nil == download->_downloadError) ? [NSData dataWithContentsOfFile:download->_destination] : nil;
|
||||
[download release];
|
||||
dispatch_release(queue);
|
||||
|
||||
return downloadData;
|
||||
}
|
||||
|
||||
- (id)initWithRequest:(NSURLRequest *)request delegate:(id <NSURLDownloadDelegate>)delegate
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil)
|
||||
{
|
||||
_request = [request retain];
|
||||
_delegate = [delegate retain];
|
||||
_startedThread = [NSThread currentThread];
|
||||
|
||||
// Set up a connection.
|
||||
_connection = [self getSandboxXPCService];
|
||||
dispatch_async(dispatch_get_current_queue(), ^{
|
||||
[self startDownload:request];
|
||||
});
|
||||
|
||||
_isDownloading = YES;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[self cancel];
|
||||
|
||||
[_request release];
|
||||
[_destination release];
|
||||
[_connectionDestination release];
|
||||
[_downloadError release];
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (NSURLRequest *)request
|
||||
{
|
||||
return _request;
|
||||
}
|
||||
|
||||
- (void)startDownload:(NSURLRequest *)urlRequest
|
||||
{
|
||||
// Send a message to download a specific url.
|
||||
if ([_delegate respondsToSelector:@selector(download:decideDestinationWithSuggestedFilename:)] && _destination == nil)
|
||||
{
|
||||
void (^block)(void) = ^{
|
||||
[_delegate download:(NSURLDownload *)self decideDestinationWithSuggestedFilename:[[urlRequest URL] lastPathComponent]];
|
||||
};
|
||||
[self performBlock:block onThread:_startedThread synchronous:YES];
|
||||
}
|
||||
if (nil == _destination)
|
||||
{
|
||||
_destination = [[[urlRequest URL] lastPathComponent] copy];
|
||||
}
|
||||
|
||||
// ivar 'destination' now contains the destination URL.
|
||||
|
||||
NSURL *tempFolder = [NSURL fileURLWithPath:NSTemporaryDirectory()];
|
||||
NSString *tempFileTemplate = [[tempFolder URLByAppendingPathComponent:kSUFetchFolderName] path];
|
||||
NSString *tempFilePath = [tempFileTemplate stringByAppendingPathComponent:[_destination lastPathComponent]];
|
||||
|
||||
NSFileManager *fileManager = [NSFileManager defaultManager];
|
||||
if ([fileManager fileExistsAtPath:tempFilePath])
|
||||
[fileManager removeItemAtPath:tempFilePath error:nil];
|
||||
|
||||
_connectionDestination = [tempFilePath copy];
|
||||
|
||||
NSData *requestData = [NSKeyedArchiver archivedDataWithRootObject:urlRequest];
|
||||
|
||||
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_data(message, SUDownloadServiceURLRequestDataKey, [requestData bytes], [requestData length]);
|
||||
xpc_dictionary_set_string(message, SUDownloadServiceFilePathKey, [tempFilePath cStringUsingEncoding:NSUTF8StringEncoding]);
|
||||
xpc_dictionary_set_connection(message, SUDownloadServiceDelegateConnectionKey, _delegateConnection);
|
||||
xpc_connection_send_message_with_reply(_connection, message, dispatch_get_main_queue(), ^(xpc_object_t object) {
|
||||
xpc_type_t type = xpc_get_type(object);
|
||||
|
||||
if (type == XPC_TYPE_ERROR && nil == _downloadError)
|
||||
{
|
||||
NSString *errMessage = @"";
|
||||
if (object == XPC_ERROR_CONNECTION_INTERRUPTED)
|
||||
{
|
||||
errMessage = @"Got XPC_ERROR_CONNECTION_INTERRUPTED error.";
|
||||
}
|
||||
else if (object == XPC_ERROR_CONNECTION_INVALID)
|
||||
{
|
||||
errMessage = @"Got XPC_ERROR_CONNECTION_INVALID error.";
|
||||
}
|
||||
|
||||
NSDictionary *errInfo = [NSDictionary dictionaryWithObject:errMessage forKey:NSLocalizedDescriptionKey];
|
||||
_downloadError = [[NSError alloc] initWithDomain:SUSparkleErrorDomain code:SUXPCServiceError userInfo:errInfo];
|
||||
}
|
||||
else if (type == XPC_TYPE_DICTIONARY && noErr != xpc_dictionary_get_int64(object, SUDownloadServiceErrorCodeKey) && nil == _downloadError)
|
||||
{
|
||||
NSInteger errCode = (NSInteger)xpc_dictionary_get_int64(object, SUDownloadServiceErrorCodeKey);
|
||||
|
||||
const char *errDomainStr = xpc_dictionary_get_string(object, SUDownloadServiceErrorDomainKey);
|
||||
NSString *errDomain = errDomainStr ? [NSString stringWithUTF8String:errDomainStr] : NSCocoaErrorDomain;
|
||||
|
||||
const char *errMessage = xpc_dictionary_get_string(object, SUDownloadServiceErrorMessageKey) ? : "";
|
||||
NSDictionary *errInfo = [NSDictionary dictionaryWithObject:[NSString stringWithUTF8String:errMessage]
|
||||
forKey:NSLocalizedDescriptionKey];
|
||||
|
||||
_downloadError = [[NSError alloc] initWithDomain:errDomain code:errCode userInfo:errInfo];
|
||||
}
|
||||
|
||||
if (nil != _downloadError)
|
||||
{
|
||||
if ([_delegate respondsToSelector:@selector(download:didFailWithError:)])
|
||||
{
|
||||
void (^block)(void) = ^{
|
||||
[_delegate download:(NSURLDownload *)self didFailWithError:_downloadError];
|
||||
_isDownloading = NO;
|
||||
};
|
||||
[self performBlock:block onThread:_startedThread synchronous:NO];
|
||||
}
|
||||
else
|
||||
{
|
||||
SULog(@"SUXPCURLDownload: got download error (%d - %@)", [_downloadError code], [_downloadError localizedDescription]);
|
||||
_isDownloading = NO;
|
||||
}
|
||||
}
|
||||
});
|
||||
xpc_release(message);
|
||||
}
|
||||
|
||||
- (id <NSURLDownloadDelegate>)delegate
|
||||
{
|
||||
return _delegate;
|
||||
}
|
||||
|
||||
- (void)setDelegate:(id <NSURLDownloadDelegate>)delegate
|
||||
{
|
||||
_delegate = delegate;
|
||||
}
|
||||
|
||||
- (void)setDestination:(NSString *)path allowOverwrite:(BOOL)allowOverwrite
|
||||
{
|
||||
[_destination release];
|
||||
_destination = [path copy];
|
||||
_allowOverwrite = allowOverwrite;
|
||||
}
|
||||
|
||||
- (void)cancel
|
||||
{
|
||||
if (_connection)
|
||||
{
|
||||
xpc_connection_cancel(_connection);
|
||||
xpc_release(_connection);
|
||||
_connection = NULL;
|
||||
}
|
||||
if (_delegateConnection)
|
||||
{
|
||||
xpc_connection_cancel(_delegateConnection);
|
||||
xpc_release(_delegateConnection);
|
||||
_delegateConnection = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
- (xpc_connection_t)getSandboxXPCService
|
||||
{
|
||||
// Set up two connections, one for instructing the XPC and getting a response,
|
||||
// and another to listen for incoming connections for progress and file creation
|
||||
// notifications.
|
||||
|
||||
_connection = xpc_connection_create("com.andymatuschak.Sparkle.download-service", dispatch_get_main_queue());
|
||||
if (!_connection)
|
||||
{
|
||||
NSLog(@"Can't connect to XPC service");
|
||||
return (NULL);
|
||||
}
|
||||
|
||||
xpc_connection_set_event_handler(_connection, ^(xpc_object_t event) {
|
||||
xpc_type_t type = xpc_get_type(event);
|
||||
|
||||
if (type == XPC_TYPE_ERROR)
|
||||
{
|
||||
if (event == XPC_ERROR_CONNECTION_INTERRUPTED)
|
||||
{
|
||||
NSLog(@"Got XPC_ERROR_CONNECTION_INTERRUPTED error.");
|
||||
// The service has either cancaled itself, crashed, or been
|
||||
// terminated. The XPC connection is still valid and sending a
|
||||
// message to it will re-launch the service. If the service is
|
||||
// state-full, this is the time to initialize the new service.
|
||||
|
||||
}
|
||||
else if (event == XPC_ERROR_CONNECTION_INVALID)
|
||||
{
|
||||
NSLog(@"Got XPC_ERROR_CONNECTION_INVALID error.");
|
||||
// The service is invalid. Either the service name supplied to
|
||||
// xpc_connection_create() is incorrect or we (this process) have
|
||||
// canceled the service; we can do any cleanup of appliation
|
||||
// state at this point.
|
||||
if (_delegateConnection)
|
||||
{
|
||||
xpc_connection_cancel(_delegateConnection);
|
||||
xpc_release(_delegateConnection);
|
||||
_delegateConnection = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
dispatch_queue_t delegate_queue = dispatch_queue_create("com.andymatuschak.Sparkle.download-service-delegate", NULL);
|
||||
assert(delegate_queue != NULL);
|
||||
|
||||
_delegateConnection = xpc_connection_create(NULL, delegate_queue);
|
||||
xpc_connection_set_event_handler(_delegateConnection, ^(xpc_object_t event) {
|
||||
xpc_type_t type = xpc_get_type(event);
|
||||
|
||||
if (type == XPC_TYPE_ERROR)
|
||||
{
|
||||
if (event == XPC_ERROR_TERMINATION_IMMINENT)
|
||||
{
|
||||
NSLog(@"received XPC_ERROR_TERMINATION_IMMINENT");
|
||||
}
|
||||
else if (event == XPC_ERROR_CONNECTION_INVALID)
|
||||
{
|
||||
NSLog(@"progress connection is closed");
|
||||
dispatch_release(delegate_queue);
|
||||
}
|
||||
}
|
||||
else if (type == XPC_TYPE_CONNECTION)
|
||||
{
|
||||
xpc_connection_t peer = (xpc_connection_t)event;
|
||||
// A new anonymous connection, from an XPC service that wants to supply us with updates.
|
||||
char *queue_name = NULL;
|
||||
dispatch_queue_t peer_event_queue = dispatch_queue_create(queue_name, NULL);
|
||||
assert(peer_event_queue != NULL);
|
||||
free(queue_name);
|
||||
|
||||
xpc_connection_set_target_queue(peer, peer_event_queue);
|
||||
xpc_connection_set_event_handler(peer, ^(xpc_object_t nevent) {
|
||||
xpc_type_t ntype = xpc_get_type(nevent);
|
||||
|
||||
if (ntype == XPC_TYPE_ERROR && nevent == XPC_ERROR_CONNECTION_INVALID)
|
||||
dispatch_release(peer_event_queue);
|
||||
if (ntype != XPC_TYPE_DICTIONARY)
|
||||
return;
|
||||
|
||||
__block xpc_object_t answer = xpc_dictionary_create_reply(nevent);
|
||||
|
||||
xpc_dictionary_apply(nevent, ^bool(const char *key, xpc_object_t value) {
|
||||
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
|
||||
|
||||
if (0 == strcmp(key, SUDownloadServiceDidBeginDownloadingKey))
|
||||
{
|
||||
if ([_delegate respondsToSelector:@selector(downloadDidBegin:)])
|
||||
{
|
||||
void (^block)(void) = ^ {
|
||||
[_delegate downloadDidBegin:(NSURLDownload *)self];
|
||||
};
|
||||
[self performBlock:block onThread:_startedThread synchronous:NO];
|
||||
}
|
||||
}
|
||||
else if (0 == strcmp(key, SUDownloadServiceReceivedResponseDataKey))
|
||||
{
|
||||
if ([_delegate respondsToSelector:@selector(download:didReceiveResponse:)])
|
||||
{
|
||||
size_t dataLength = 0;
|
||||
const void * responseDataBytes = xpc_dictionary_get_data(nevent, SUDownloadServiceReceivedResponseDataKey, &dataLength);
|
||||
NSData *responseData = [NSData dataWithBytes:responseDataBytes length:(NSUInteger)dataLength];
|
||||
|
||||
NSURLResponse *response = [NSKeyedUnarchiver unarchiveObjectWithData:responseData];
|
||||
void (^block)(void) = ^ {
|
||||
[_delegate download:(NSURLDownload *)self didReceiveResponse:response];
|
||||
};
|
||||
[self performBlock:block onThread:_startedThread synchronous:NO];
|
||||
}
|
||||
}
|
||||
else if (0 == strcmp(key, SUDownloadServiceReceivedDataLengthKey))
|
||||
{
|
||||
if ([_delegate respondsToSelector:@selector(download:didReceiveDataOfLength:)])
|
||||
{
|
||||
int64_t dataLength = xpc_dictionary_get_int64(nevent, SUDownloadServiceReceivedDataLengthKey);
|
||||
void (^block)(void) = ^ {
|
||||
[_delegate download:(NSURLDownload *)self didReceiveDataOfLength:(NSUInteger)dataLength];
|
||||
};
|
||||
[self performBlock:block onThread:_startedThread synchronous:NO];
|
||||
}
|
||||
}
|
||||
else if (0 == strcmp(key, SUDownloadServiceCreatedDestinationPathKey))
|
||||
{
|
||||
[_connectionDestination release];
|
||||
_connectionDestination = [[NSString alloc] initWithCString:xpc_dictionary_get_string(nevent, SUDownloadServiceCreatedDestinationPathKey)
|
||||
encoding:NSUTF8StringEncoding];
|
||||
}
|
||||
else if (0 == strcmp(key, SUDownloadServiceReceivedFailErrorKey))
|
||||
{
|
||||
size_t dataLength = 0;
|
||||
const void * errorDataBytes = xpc_dictionary_get_data(nevent, SUDownloadServiceReceivedFailErrorKey, &dataLength);
|
||||
NSData *errorData = [NSData dataWithBytes:errorDataBytes length:dataLength];
|
||||
|
||||
NSError *error = [NSKeyedUnarchiver unarchiveObjectWithData:errorData];
|
||||
_downloadError = [error retain];
|
||||
}
|
||||
else if (0 == strcmp(key, SUDownloadServiceDidFinishDownloadingKey))
|
||||
{
|
||||
NSFileManager *fileManager = [NSFileManager defaultManager];
|
||||
|
||||
NSString *destPath = _destination;
|
||||
if (nil == destPath || [destPath isEqualToString:[destPath lastPathComponent]])
|
||||
{
|
||||
destPath = _connectionDestination;
|
||||
}
|
||||
else if (!_allowOverwrite)
|
||||
{
|
||||
NSUInteger index = 1;
|
||||
NSString *parentFolder = [destPath stringByDeletingLastPathComponent];
|
||||
NSString *initialFileName = [[destPath lastPathComponent] stringByDeletingPathExtension];
|
||||
NSString *fileExtension = [destPath pathExtension];
|
||||
|
||||
while ([fileManager fileExistsAtPath:destPath])
|
||||
{
|
||||
NSString *fileName = [initialFileName stringByAppendingFormat:@"_%ld", index];
|
||||
destPath = [[parentFolder stringByAppendingPathComponent:fileName] stringByAppendingPathExtension:fileExtension];
|
||||
++index;
|
||||
}
|
||||
}
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = YES;
|
||||
|
||||
if (![destPath isEqualToString:_connectionDestination])
|
||||
{
|
||||
success = success && [fileManager createDirectoryAtPath:[destPath stringByDeletingLastPathComponent]
|
||||
withIntermediateDirectories:YES
|
||||
attributes:nil
|
||||
error:&error];
|
||||
if (success && [fileManager fileExistsAtPath:destPath])
|
||||
success = [fileManager removeItemAtPath:destPath error:&error];
|
||||
success = success && [fileManager moveItemAtPath:_connectionDestination toPath:destPath error:&error];
|
||||
}
|
||||
|
||||
if (success)
|
||||
{
|
||||
[self setDestination:destPath allowOverwrite:_allowOverwrite];
|
||||
|
||||
void (^block)(void) = ^ {
|
||||
if ([_delegate respondsToSelector:@selector(download:didCreateDestination:)])
|
||||
[_delegate download:(NSURLDownload *)self didCreateDestination:destPath];
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(downloadDidFinish:)])
|
||||
[_delegate downloadDidFinish:(NSURLDownload *)self];
|
||||
|
||||
_isDownloading = NO;
|
||||
};
|
||||
[self performBlock:block onThread:_startedThread synchronous:NO];
|
||||
}
|
||||
else
|
||||
{
|
||||
_downloadError = [error retain];
|
||||
}
|
||||
}
|
||||
else if (0 == strcmp(key, SUDownloadServiceMIMETypeToDecodeKey))
|
||||
{
|
||||
void (^block)(void) = ^{
|
||||
BOOL shouldDecode = NO;
|
||||
if ([_delegate respondsToSelector:@selector(download:shouldDecodeSourceDataOfMIMEType:)])
|
||||
{
|
||||
NSString *MIMEType = [NSString stringWithCString:xpc_dictionary_get_string(nevent, SUDownloadServiceMIMETypeToDecodeKey)
|
||||
encoding:NSUTF8StringEncoding];
|
||||
shouldDecode = [_delegate download:(NSURLDownload *)self shouldDecodeSourceDataOfMIMEType:MIMEType];
|
||||
}
|
||||
xpc_dictionary_set_bool(answer, SUDownloadServiceShouldDecodeMIMETypeKey, YES);
|
||||
};
|
||||
[self performBlock:block onThread:_startedThread synchronous:YES];
|
||||
}
|
||||
|
||||
[localPool release];
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
xpc_connection_send_message(peer, answer);
|
||||
xpc_release(answer);
|
||||
});
|
||||
xpc_connection_resume(peer);
|
||||
}
|
||||
});
|
||||
|
||||
// Need to resume the service in order for it to process messages.
|
||||
xpc_connection_resume(_delegateConnection);
|
||||
xpc_connection_resume(_connection);
|
||||
return _connection;
|
||||
}
|
||||
|
||||
#pragma mark - Private
|
||||
|
||||
- (void)performBlock:(void (^)(void))block onThread:(NSThread *)thread synchronous:(BOOL)flag
|
||||
{
|
||||
void (^blockCopy)(void) = block != NULL ? Block_copy(block) : NULL;
|
||||
[self performSelector:@selector(fireBlock:) onThread:thread withObject:blockCopy waitUntilDone:flag];
|
||||
}
|
||||
|
||||
- (void)fireBlock:(void (^)(void))block
|
||||
{
|
||||
if (NULL == block)
|
||||
return;
|
||||
|
||||
block();
|
||||
Block_release(block);
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,265 @@
|
||||
//
|
||||
// main.m
|
||||
// Downloading XPC Service
|
||||
//
|
||||
// Created by Erik Aderstedt on 2012-08-09.
|
||||
// Based on the Apple sample code 'SandboxedFetch'.
|
||||
//
|
||||
|
||||
#import <xpc/xpc.h>
|
||||
#import <asl.h>
|
||||
#import <assert.h>
|
||||
#import <errno.h>
|
||||
#import <stdio.h>
|
||||
|
||||
#import "SUDownloadServiceConstants.h"
|
||||
#import "SUDSDownloader.h"
|
||||
#import "SUConstants.h"
|
||||
|
||||
static void fetch_process_request(xpc_object_t request, xpc_object_t reply);
|
||||
static void fetch_peer_event_handler(xpc_connection_t peer, xpc_object_t event);
|
||||
static void fetch_event_handler(xpc_connection_t peer);
|
||||
|
||||
#pragma mark -
|
||||
|
||||
// Process the XPC request, create a temporary file to hold downloaded,
|
||||
// data, and build/return XPC reply.
|
||||
static void fetch_process_request(xpc_object_t request, xpc_object_t reply)
|
||||
{
|
||||
__block int32_t errcode = 0;
|
||||
__block const char *errmsg = NULL;
|
||||
__block const char *errdomain = NULL;
|
||||
|
||||
xpc_connection_t connection = NULL;
|
||||
|
||||
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
|
||||
do
|
||||
{
|
||||
size_t dataLength = 0;
|
||||
const void *data = xpc_dictionary_get_data(request, SUDownloadServiceURLRequestDataKey, &dataLength);
|
||||
NSData *requestData = [NSData dataWithBytes:data length:dataLength];
|
||||
|
||||
NSURLRequest *urlRequest = [NSKeyedUnarchiver unarchiveObjectWithData:requestData];
|
||||
if (nil == urlRequest)
|
||||
{
|
||||
errcode = SUXPCServiceError;
|
||||
errdomain = [SUSparkleErrorDomain cStringUsingEncoding:NSUTF8StringEncoding];
|
||||
errmsg = "Invalid URL request data";
|
||||
break;
|
||||
}
|
||||
|
||||
// Get the URL and XPC connection from the XPC request
|
||||
connection = xpc_dictionary_create_connection(request, SUDownloadServiceDelegateConnectionKey);
|
||||
if (connection == NULL)
|
||||
{
|
||||
errcode = SUXPCServiceError;
|
||||
errdomain = [SUSparkleErrorDomain cStringUsingEncoding:NSUTF8StringEncoding];
|
||||
errmsg = "Invalid XPC delegate connection";
|
||||
break;
|
||||
}
|
||||
|
||||
// Set up XPC connection endpoint for sending progress reports and receiving cancel notification.
|
||||
__block BOOL shouldStopDownload = NO;
|
||||
xpc_connection_set_event_handler(connection, ^(xpc_object_t event) {
|
||||
xpc_type_t type = xpc_get_type(event);
|
||||
|
||||
// If the remote end of this connection has gone away then stop download
|
||||
if (XPC_TYPE_ERROR == type &&
|
||||
(XPC_ERROR_CONNECTION_INTERRUPTED == event || XPC_ERROR_CONNECTION_INVALID == event))
|
||||
{
|
||||
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "Stopping download process...\n");
|
||||
shouldStopDownload = YES;
|
||||
}
|
||||
});
|
||||
xpc_connection_resume(connection);
|
||||
|
||||
NSString *destinationPath = [NSString stringWithCString:xpc_dictionary_get_string(request, SUDownloadServiceFilePathKey)
|
||||
encoding:NSUTF8StringEncoding];
|
||||
SUDSDownloader *downloader = [SUDSDownloader downloaderWithURLRequest:urlRequest
|
||||
destinationPath:destinationPath];
|
||||
|
||||
SUDSDownloaderCallBacks callBacks = {0};
|
||||
|
||||
callBacks.downloadDidReceiveData = ^(SUDSDownloader *downloader, NSUInteger dataLength) {
|
||||
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_int64(message, SUDownloadServiceReceivedDataLengthKey, (int64_t)dataLength);
|
||||
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
|
||||
xpc_release(message);
|
||||
xpc_release(answer);
|
||||
};
|
||||
|
||||
callBacks.downloadDidReceiveResponse = ^(SUDSDownloader *downloader, NSURLResponse *response) {
|
||||
NSData *responseData = [NSKeyedArchiver archivedDataWithRootObject:response];
|
||||
|
||||
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_data(message, SUDownloadServiceReceivedResponseDataKey, [responseData bytes], [responseData length]);
|
||||
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
|
||||
xpc_release(message);
|
||||
xpc_release(answer);
|
||||
};
|
||||
|
||||
callBacks.downloadDidCreateDestination = ^(SUDSDownloader *downloader, NSString *destinationPath) {
|
||||
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_string(message, SUDownloadServiceCreatedDestinationPathKey, [destinationPath cStringUsingEncoding:NSUTF8StringEncoding]);
|
||||
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
|
||||
xpc_release(message);
|
||||
xpc_release(answer);
|
||||
};
|
||||
|
||||
callBacks.downloadDidBegin = ^(SUDSDownloader *downloader) {
|
||||
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_bool(message, SUDownloadServiceDidBeginDownloadingKey, true);
|
||||
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
|
||||
xpc_release(message);
|
||||
xpc_release(answer);
|
||||
};
|
||||
|
||||
callBacks.downloadDidFail = ^(SUDSDownloader *downloader, NSError *error) {
|
||||
errcode = (int32_t)[error code];
|
||||
errdomain = [[error domain] cStringUsingEncoding:NSUTF8StringEncoding];
|
||||
errmsg = [[error localizedDescription] cStringUsingEncoding:NSUTF8StringEncoding];
|
||||
|
||||
NSData *errorData = [NSKeyedArchiver archivedDataWithRootObject:error];
|
||||
|
||||
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_data(message, SUDownloadServiceReceivedFailErrorKey, [errorData bytes], [errorData length]);
|
||||
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
|
||||
xpc_release(message);
|
||||
xpc_release(answer);
|
||||
};
|
||||
|
||||
callBacks.downloadDidFinish = ^(SUDSDownloader *downloader) {
|
||||
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_bool(message, SUDownloadServiceDidFinishDownloadingKey, true);
|
||||
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
|
||||
xpc_release(message);
|
||||
xpc_release(answer);
|
||||
};
|
||||
|
||||
callBacks.downloadShouldDecodeSourceData = ^BOOL(SUDSDownloader *downloader, NSString *MIMEType) {
|
||||
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_string(message, SUDownloadServiceMIMETypeToDecodeKey, [MIMEType cStringUsingEncoding:NSUTF8StringEncoding]);
|
||||
xpc_object_t answer = xpc_connection_send_message_with_reply_sync(connection, message);
|
||||
xpc_release(message);
|
||||
|
||||
BOOL result = NO;
|
||||
if (xpc_get_type(answer) == XPC_TYPE_DICTIONARY)
|
||||
result = (BOOL)xpc_dictionary_get_bool(answer, SUDownloadServiceShouldDecodeMIMETypeKey);
|
||||
xpc_release(answer);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
[downloader setCallBacks:callBacks];
|
||||
|
||||
[downloader startDownload];
|
||||
while ([downloader isInProgress])
|
||||
{
|
||||
if (shouldStopDownload)
|
||||
{
|
||||
[downloader stopDownload];
|
||||
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "Download process stopped.\n");
|
||||
break;
|
||||
}
|
||||
|
||||
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
|
||||
}
|
||||
}
|
||||
while (NO);
|
||||
[localPool release];
|
||||
|
||||
#if DEBUG_LOGGING_ENABLED
|
||||
NSLog(@"Download process finished. Will send last message...");
|
||||
#endif
|
||||
// Clean up and add errcode/errmsg to reply
|
||||
if (connection)
|
||||
{
|
||||
xpc_connection_cancel(connection);
|
||||
xpc_release(connection);
|
||||
}
|
||||
|
||||
xpc_dictionary_set_int64(reply, SUDownloadServiceErrorCodeKey, (int64_t)errcode);
|
||||
if (errmsg)
|
||||
{
|
||||
xpc_dictionary_set_string(reply, SUDownloadServiceErrorMessageKey, errmsg);
|
||||
}
|
||||
if (errdomain)
|
||||
{
|
||||
xpc_dictionary_set_string(reply, SUDownloadServiceErrorDomainKey, errdomain);
|
||||
}
|
||||
}
|
||||
|
||||
static void fetch_peer_event_handler(xpc_connection_t peer, xpc_object_t event)
|
||||
{
|
||||
// Get the object type.
|
||||
xpc_type_t type = xpc_get_type(event);
|
||||
if (XPC_TYPE_ERROR == type)
|
||||
{
|
||||
// Handle an error.
|
||||
if (XPC_ERROR_CONNECTION_INVALID == event)
|
||||
{
|
||||
// The client process on the other end of the connection
|
||||
// has either crashed or cancelled the connection.
|
||||
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "peer(%d) received "
|
||||
"XPC_ERROR_CONNECTION_INVALID",
|
||||
xpc_connection_get_pid(peer));
|
||||
xpc_connection_cancel(peer);
|
||||
}
|
||||
else if (XPC_ERROR_TERMINATION_IMMINENT == event)
|
||||
{
|
||||
// Handle per-connection termination cleanup. This
|
||||
// service is about to exit.
|
||||
asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "peer(%d) received "
|
||||
"XPC_ERROR_TERMINATION_IMMINENT",
|
||||
xpc_connection_get_pid(peer));
|
||||
}
|
||||
}
|
||||
else if (XPC_TYPE_DICTIONARY == type)
|
||||
{
|
||||
xpc_object_t requestMessage = event;
|
||||
xpc_object_t replyMessage = xpc_dictionary_create_reply(requestMessage);
|
||||
assert(replyMessage != NULL);
|
||||
|
||||
// Process request and build a reply message.
|
||||
fetch_process_request(requestMessage, replyMessage);
|
||||
|
||||
xpc_connection_send_message(peer, replyMessage);
|
||||
xpc_release(replyMessage);
|
||||
}
|
||||
}
|
||||
|
||||
static void release_dispatch_queue(void *queue)
|
||||
{
|
||||
dispatch_release(queue);
|
||||
}
|
||||
|
||||
static void fetch_event_handler(xpc_connection_t peer)
|
||||
{
|
||||
// Generate an unique name for the queue to handle messages from
|
||||
// this peer and create a new dispatch queue for it.
|
||||
char *queue_name = NULL;
|
||||
asprintf(&queue_name, "%s-peer-%d", "com.andymatuschak.Sparkle.download-service", xpc_connection_get_pid(peer));
|
||||
dispatch_queue_t peer_event_queue = dispatch_queue_create(queue_name, DISPATCH_QUEUE_SERIAL);
|
||||
assert(peer_event_queue != NULL);
|
||||
free(queue_name);
|
||||
|
||||
// Set the target queue for connection.
|
||||
xpc_connection_set_target_queue(peer, peer_event_queue);
|
||||
xpc_connection_set_context(peer, peer_event_queue);
|
||||
xpc_connection_set_finalizer_f(peer, release_dispatch_queue);
|
||||
|
||||
// Set the handler block for connection.
|
||||
xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {
|
||||
fetch_peer_event_handler(peer, event);
|
||||
});
|
||||
|
||||
// Enable the peer connection to receive messages.
|
||||
xpc_connection_resume(peer);
|
||||
}
|
||||
|
||||
int main(int argc, const char *argv[])
|
||||
{
|
||||
xpc_main(fetch_event_handler);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/* Localized versions of Info.plist keys */
|
||||
|
||||
Vendored
BIN
Binary file not shown.
+2
-2
@@ -19,9 +19,9 @@
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1.5</string>
|
||||
<string>${DYLIB_CURRENT_VERSION}</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.5 Beta (bzr)</string>
|
||||
<string>${DYLIB_CURRENT_VERSION}</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//
|
||||
// SUInstallServiceConstants.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Dmytro Tretiakov on 8/2/13.
|
||||
//
|
||||
//
|
||||
|
||||
#ifndef Sparkle_SUInstallServiceConstants_h
|
||||
#define Sparkle_SUInstallServiceConstants_h
|
||||
|
||||
typedef enum _SUInstallSerciveTask
|
||||
{
|
||||
SUInstallServiceTaskCopyPath = 1LL,
|
||||
SUInstallServiceTaskLaunchTask = 2LL
|
||||
} SUInstallServiceTask;
|
||||
|
||||
const char * SUInstallServiceTaskTypeKey = "task_type"; // int64_t
|
||||
|
||||
// SUInstallServiceTaskCopyPath keys
|
||||
const char * SUInstallServiceSourcePathKey = "source_path"; // c-string
|
||||
const char * SUInstallServiceDestinationPathKey = "destination_path"; // c-string
|
||||
const char * SUInstallServiceTempNameKey = "tmp_name"; // c-string
|
||||
|
||||
// SUInstallServiceTaskLaunchTask keys
|
||||
const char * SUInstallServiceLaunchTaksPathKey = "launch_task_path";
|
||||
const char * SUInstallServiceLaunchTaskArgumentsKey = "launch_task_arguments"; // xpc_array of c-strings
|
||||
|
||||
// Reply keys
|
||||
const char * SUInstallServiceErrorCodeKey = "error_code"; // int64_t
|
||||
const char * SUInstallServiceErrorLocalizedDescriptionKey = "error_localized_description"; // c-string
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,16 @@
|
||||
//
|
||||
// SUXPCInstaller.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Whitney Young on 3/19/12.
|
||||
// Copyright (c) 2012 FadingRed. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface SUXPCInstaller : NSObject
|
||||
|
||||
+ (void)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp completionHandler:(void (^)(NSError *error))completionHandler;
|
||||
+ (void)launchTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments completionHandler:(void (^)(void))completionHandler ;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,107 @@
|
||||
//
|
||||
// SUXPCInstaller.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Whitney Young on 3/19/12.
|
||||
// Copyright (c) 2012 FadingRed. All rights reserved.
|
||||
//
|
||||
|
||||
#import <xpc/xpc.h>
|
||||
#import "SUXPCInstaller.h"
|
||||
#import "SUInstallServiceConstants.h"
|
||||
|
||||
|
||||
@implementation SUXPCInstaller
|
||||
|
||||
+ (xpc_connection_t)getSandboxXPCService
|
||||
{
|
||||
__block xpc_connection_t serviceConnection = xpc_connection_create("com.andymatuschak.Sparkle.install-service", dispatch_get_main_queue());
|
||||
|
||||
if (!serviceConnection)
|
||||
{
|
||||
NSLog(@"Can't connect to XPC service");
|
||||
return (NULL);
|
||||
}
|
||||
|
||||
xpc_connection_set_event_handler(serviceConnection, ^(xpc_object_t event) {
|
||||
xpc_type_t type = xpc_get_type(event);
|
||||
|
||||
if (type == XPC_TYPE_ERROR)
|
||||
{
|
||||
if (event == XPC_ERROR_CONNECTION_INVALID)
|
||||
{
|
||||
// The service is invalid. Either the service name supplied to
|
||||
// xpc_connection_create() is incorrect or we (this process) have
|
||||
// canceled the service; we can do any cleanup of appliation
|
||||
// state at this point.
|
||||
xpc_release(serviceConnection);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Need to resume the service in order for it to process messages.
|
||||
xpc_connection_resume(serviceConnection);
|
||||
return (serviceConnection);
|
||||
}
|
||||
|
||||
+ (void)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp completionHandler:(void (^)(NSError *error))completionHandler
|
||||
{
|
||||
xpc_connection_t connection = [self getSandboxXPCService];
|
||||
|
||||
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskCopyPath);
|
||||
|
||||
if (src)
|
||||
xpc_dictionary_set_string(message, SUInstallServiceSourcePathKey, [src fileSystemRepresentation]);
|
||||
if (dst)
|
||||
xpc_dictionary_set_string(message, SUInstallServiceDestinationPathKey, [dst fileSystemRepresentation]);
|
||||
if (tmp)
|
||||
xpc_dictionary_set_string(message, SUInstallServiceTempNameKey, [tmp UTF8String]);
|
||||
|
||||
xpc_connection_send_message_with_reply(connection, message, dispatch_get_main_queue(), ^(xpc_object_t response) {
|
||||
if (NULL == completionHandler)
|
||||
return;
|
||||
|
||||
const char *errorString = xpc_dictionary_get_string(response, SUInstallServiceErrorLocalizedDescriptionKey);
|
||||
if (errorString != NULL)
|
||||
{
|
||||
NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain
|
||||
code:SUXPCServiceError
|
||||
userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithCString:errorString encoding:NSUTF8StringEncoding]
|
||||
forKey:NSLocalizedDescriptionKey]];
|
||||
completionHandler(error);
|
||||
}
|
||||
else
|
||||
{
|
||||
completionHandler(nil);
|
||||
}
|
||||
});
|
||||
xpc_release(message);
|
||||
}
|
||||
|
||||
+ (void)launchTaskWithLaunchPath:(NSString *)path arguments:(NSArray *)arguments completionHandler:(void (^)(void))completionHandler
|
||||
{
|
||||
xpc_connection_t connection = [self getSandboxXPCService];
|
||||
|
||||
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_int64(message, SUInstallServiceTaskTypeKey, (int64_t)SUInstallServiceTaskLaunchTask);
|
||||
|
||||
if (path)
|
||||
xpc_dictionary_set_string(message, SUInstallServiceLaunchTaksPathKey, [path fileSystemRepresentation]);
|
||||
|
||||
xpc_object_t array = xpc_array_create(NULL, 0);
|
||||
for (id argument in arguments)
|
||||
{
|
||||
xpc_array_set_string(array, XPC_ARRAY_APPEND, [argument UTF8String]);
|
||||
}
|
||||
xpc_dictionary_set_value(message, SUInstallServiceLaunchTaskArgumentsKey, array);
|
||||
xpc_release(array);
|
||||
|
||||
xpc_connection_send_message_with_reply(connection, message, dispatch_get_current_queue(), ^(xpc_object_t response) {
|
||||
if (completionHandler != NULL)
|
||||
completionHandler();
|
||||
});
|
||||
xpc_release(message);
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,31 @@
|
||||
<?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>CFBundleDevelopmentRegion</key>
|
||||
<string>English</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>XPC!</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>XPCService</key>
|
||||
<dict>
|
||||
<key>ServiceType</key>
|
||||
<string>Application</string>
|
||||
<key>JoinExistingSession</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,127 @@
|
||||
//
|
||||
// main.m
|
||||
// Update
|
||||
//
|
||||
// Created by Whitney Young on 3/19/12.
|
||||
// Copyright (c) 2012 FadingRed. All rights reserved.
|
||||
//
|
||||
|
||||
#include <xpc/xpc.h>
|
||||
#include <asl.h>
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUPlainInstallerInternals.h"
|
||||
#import "SUInstallServiceConstants.h"
|
||||
#import "SULog.h"
|
||||
|
||||
static void peer_event_handler(xpc_connection_t peer, xpc_object_t event)
|
||||
{
|
||||
xpc_type_t type = xpc_get_type(event);
|
||||
if (type == XPC_TYPE_ERROR)
|
||||
{
|
||||
if (event == XPC_ERROR_CONNECTION_INVALID)
|
||||
{
|
||||
// The client process on the other end of the connection has either
|
||||
// crashed or cancelled the connection. After receiving this error,
|
||||
// the connection is in an invalid state, and you do not need to
|
||||
// call xpc_connection_cancel(). Just tear down any associated state
|
||||
// here.
|
||||
}
|
||||
else if (event == XPC_ERROR_TERMINATION_IMMINENT)
|
||||
{
|
||||
// Handle per-connection termination cleanup.
|
||||
}
|
||||
}
|
||||
else if (type == XPC_TYPE_DICTIONARY)
|
||||
{
|
||||
// Handle the message.
|
||||
SUInstallServiceTask task = (SUInstallServiceTask)xpc_dictionary_get_int64(event, SUInstallServiceTaskTypeKey);
|
||||
|
||||
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
|
||||
switch (task)
|
||||
{
|
||||
case SUInstallServiceTaskCopyPath:
|
||||
{
|
||||
const char *src = xpc_dictionary_get_string(event, SUInstallServiceSourcePathKey);
|
||||
const char *dst = xpc_dictionary_get_string(event, SUInstallServiceDestinationPathKey);
|
||||
const char *tmp = xpc_dictionary_get_string(event, SUInstallServiceTempNameKey);
|
||||
|
||||
NSFileManager *manager = [NSFileManager defaultManager];
|
||||
NSString *relaunchPathToCopy = src ? [manager stringWithFileSystemRepresentation:src length:strlen(src)] : nil;
|
||||
NSString *targetPath = dst ? [manager stringWithFileSystemRepresentation:dst length:strlen(dst)] : nil;
|
||||
NSString *temporaryName = tmp ? [NSString stringWithUTF8String:tmp] : nil;
|
||||
NSError *error = nil;
|
||||
BOOL result = [SUPlainInstaller copyPathWithAuthentication: relaunchPathToCopy overPath: targetPath temporaryName: temporaryName error: &error];
|
||||
|
||||
// send response to indicate ok
|
||||
xpc_object_t reply = xpc_dictionary_create_reply(event);
|
||||
if (!result && error != nil)
|
||||
{
|
||||
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, [error code]);
|
||||
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, [[error localizedDescription] cStringUsingEncoding:NSUTF8StringEncoding]);
|
||||
}
|
||||
xpc_connection_send_message(peer, reply);
|
||||
xpc_release(reply);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case SUInstallServiceTaskLaunchTask:
|
||||
{
|
||||
const char *path = xpc_dictionary_get_string(event, SUInstallServiceLaunchTaksPathKey);
|
||||
xpc_object_t array = xpc_dictionary_get_value(event, SUInstallServiceLaunchTaskArgumentsKey);
|
||||
|
||||
NSFileManager *manager = [NSFileManager defaultManager];
|
||||
NSString *relaunchToolPath = path ? [manager stringWithFileSystemRepresentation:path length:strlen(path)] : nil;;
|
||||
NSMutableArray *arguments = [NSMutableArray array];
|
||||
for (size_t i = 0; i < xpc_array_get_count(array); i++)
|
||||
{
|
||||
[arguments addObject:[NSString stringWithUTF8String:xpc_array_get_string(array, i)]];
|
||||
}
|
||||
|
||||
[NSTask launchedTaskWithLaunchPath:relaunchToolPath arguments:arguments];
|
||||
|
||||
// send response to indicate ok
|
||||
xpc_object_t reply = xpc_dictionary_create_reply(event);
|
||||
xpc_connection_send_message(peer, reply);
|
||||
xpc_release(reply);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
SULog(@"XPC Install Service: Unknown XPC service task %lld", (int64_t)task);
|
||||
|
||||
xpc_object_t reply = xpc_dictionary_create_reply(event);
|
||||
xpc_dictionary_set_int64(reply, SUInstallServiceErrorCodeKey, (int64_t)1);
|
||||
xpc_dictionary_set_string(reply, SUInstallServiceErrorLocalizedDescriptionKey, "Unknown install cervice task.");
|
||||
xpc_connection_send_message(peer, reply);
|
||||
xpc_release(reply);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
[localPool release];
|
||||
}
|
||||
}
|
||||
|
||||
static void event_handler(xpc_connection_t peer)
|
||||
{
|
||||
// By defaults, new connections will target the default dispatch
|
||||
// concurrent queue.
|
||||
xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {
|
||||
peer_event_handler(peer, event);
|
||||
});
|
||||
|
||||
// This will tell the connection to begin listening for events. If you
|
||||
// have some other initialization that must be done asynchronously, then
|
||||
// you can defer this call until after that initialization is done.
|
||||
xpc_connection_resume(peer);
|
||||
}
|
||||
|
||||
int main(int argc, const char *argv[])
|
||||
{
|
||||
xpc_main(event_handler);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//
|
||||
// install_service.pch
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Dmytro Tretiakov on 4/25/14.
|
||||
//
|
||||
//
|
||||
|
||||
#define SPARKLE_BUNDLE [NSBundle mainBundle]
|
||||
#define SULocalizedString(key,comment) NSLocalizedStringFromTableInBundle(key, @"Sparkle", SPARKLE_BUNDLE, comment)
|
||||
|
||||
+32
-1
@@ -4,4 +4,35 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
=================
|
||||
EXTERNAL LICENSES
|
||||
=================
|
||||
|
||||
License for bspatch.c and bsdiff.c, from bsdiff 4.3 (<http://www.daemonology.net/bsdiff/>:
|
||||
/*-
|
||||
* Copyright 2003-2005 Colin Percival
|
||||
* All rights reserved
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted providing that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
|
||||
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
|
||||
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
@@ -1,59 +0,0 @@
|
||||
//
|
||||
// NSBundle+SUAdditions.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 12/21/07.
|
||||
// Copyright 2007 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef NSBUNDLE_PLUS_ADDITIONS_H
|
||||
#define NSBUNDLE_PLUS_ADDITIONS_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@interface NSBundle (SUAdditions)
|
||||
/*!
|
||||
@method
|
||||
@abstract Returns a name for the bundle suitable for display to the user.
|
||||
@discussion This is performed by asking NSFileManager for the display name of the bundle.
|
||||
*/
|
||||
- (NSString *)name;
|
||||
|
||||
/*!
|
||||
@method
|
||||
@abstract Returns the current internal version of the bundle.
|
||||
@discussion This uses the CFBundleVersion info value. This string is not appropriate for display to users: use -displayVersion instead.
|
||||
*/
|
||||
- (NSString *)version;
|
||||
|
||||
/*!
|
||||
@method
|
||||
@abstract Returns the bundle's version, suitable for display to the user.
|
||||
@discussion If the CFBundleShortVersionString is available and different from the CFBundleVersion, this looks like CFBundleShortVersionString (CFBundleVersion). If the version strings are the same or CFBundleShortVersionString is not defined, this is equivalent to -version.
|
||||
*/
|
||||
- (NSString *)displayVersion;
|
||||
|
||||
/*!
|
||||
@method
|
||||
@abstract Returns a suitable icon for this bundle.
|
||||
@discussion Uses the CFBundleIconFile icon if defined; otherwise, uses the default application icon.
|
||||
*/
|
||||
- (NSImage *)icon;
|
||||
|
||||
/*!
|
||||
@method
|
||||
@abstract Returns whether the application is running from a disk image.
|
||||
*/
|
||||
- (BOOL)isRunningFromDiskImage;
|
||||
|
||||
/*!
|
||||
@method
|
||||
@abstract Returns a profile of the users system useful for statistical purposes.
|
||||
@discussion Returns an array of dictionaries; each dictionary represents a piece of data and has keys "key", "visibleKey", "value", and "visibleValue".
|
||||
*/
|
||||
- (NSArray *)systemProfile;
|
||||
|
||||
- (NSString *)publicDSAKey;
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,89 +0,0 @@
|
||||
//
|
||||
// NSBundle+SUAdditions.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 12/21/07.
|
||||
// Copyright 2007 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "NSBundle+SUAdditions.h"
|
||||
|
||||
#ifndef NSAppKitVersionNumber10_4
|
||||
#define NSAppKitVersionNumber10_4 824
|
||||
#endif
|
||||
|
||||
@implementation NSBundle (SUAdditions)
|
||||
|
||||
- (NSString *)name
|
||||
{
|
||||
NSString *name = [self objectForInfoDictionaryKey:@"CFBundleDisplayName"];
|
||||
if (name) return name;
|
||||
|
||||
name = [self objectForInfoDictionaryKey:@"CFBundleName"];
|
||||
if (name) return name;
|
||||
|
||||
return [[[NSFileManager defaultManager] displayNameAtPath:[self bundlePath]] stringByDeletingPathExtension];
|
||||
}
|
||||
|
||||
- (NSString *)version
|
||||
{
|
||||
return [self objectForInfoDictionaryKey:@"CFBundleVersion"];
|
||||
}
|
||||
|
||||
- (NSString *)displayVersion
|
||||
{
|
||||
NSString *shortVersionString = [self objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
|
||||
if (shortVersionString)
|
||||
return shortVersionString;
|
||||
else
|
||||
return [self version]; // Fall back on the normal version string.
|
||||
}
|
||||
|
||||
- (NSImage *)icon
|
||||
{
|
||||
// Cache the application icon.
|
||||
NSString *iconPath = [self pathForResource:[self objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"];
|
||||
// According to the OS X docs, "CFBundleIconFile - This key identifies the file containing
|
||||
// the icon for the bundle. The filename you specify does not need to include the .icns
|
||||
// extension, although it may."
|
||||
//
|
||||
// However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try:
|
||||
if (!iconPath)
|
||||
iconPath = [self pathForResource:[self objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType: nil];
|
||||
NSImage *icon = [[[NSImage alloc] initWithContentsOfFile:iconPath] autorelease];
|
||||
// Use a default icon if none is defined.
|
||||
if (!icon) { [[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kGenericApplicationIcon)]; }
|
||||
return icon;
|
||||
}
|
||||
|
||||
- (BOOL)isRunningFromDiskImage
|
||||
{
|
||||
// This check causes crashes on 10.3; for now, we'll just skip it.
|
||||
if (floor(NSAppKitVersionNumber) < NSAppKitVersionNumber10_4)
|
||||
return NO;
|
||||
|
||||
NSDictionary *pathProperties = [[NSWorkspace sharedWorkspace] propertiesForPath:[self bundlePath]];
|
||||
BOOL isDiskImage = [pathProperties objectForKey:NSWorkspace_RBimagefilepath] != nil;
|
||||
BOOL isFileVault = [[pathProperties objectForKey:NSWorkspace_RBmntonname] hasPrefix:@"/Users/"];
|
||||
return isDiskImage && !isFileVault;
|
||||
}
|
||||
|
||||
- (NSString *)publicDSAKey
|
||||
{
|
||||
// Maybe the key is just a string in the Info.plist.
|
||||
NSString *key = [self objectForInfoDictionaryKey:SUPublicDSAKeyKey];
|
||||
if (key) { return key; }
|
||||
|
||||
// More likely, we've got a reference to a Resources file by filename:
|
||||
NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
|
||||
if (!keyFilename) { return nil; }
|
||||
return [NSString stringWithContentsOfFile:[self pathForResource:keyFilename ofType:nil]];
|
||||
}
|
||||
|
||||
- (NSArray *)systemProfile
|
||||
{
|
||||
return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHostBundle:self];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,18 +0,0 @@
|
||||
//
|
||||
// NSFileManager+Aliases.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 2/4/08.
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef NSFILEMANAGER_PLUS_ALIASES_H
|
||||
#define NSFILEMANAGER_PLUS_ALIASES_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@interface NSFileManager (SUAliases)
|
||||
- (BOOL)isAliasFolderAtPath:(NSString *)path;
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,33 +0,0 @@
|
||||
//
|
||||
// NSFileManager+Aliases.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 2/4/08.
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "NSFileManager+Aliases.h"
|
||||
|
||||
|
||||
@implementation NSFileManager (SUAliases)
|
||||
|
||||
- (BOOL)isAliasFolderAtPath:(NSString *)path
|
||||
{
|
||||
FSRef fileRef;
|
||||
OSStatus err = noErr;
|
||||
Boolean aliasFileFlag, folderFlag;
|
||||
NSURL *fileURL = [NSURL fileURLWithPath:path];
|
||||
|
||||
if (FALSE == CFURLGetFSRef((CFURLRef)fileURL, &fileRef))
|
||||
err = coreFoundationUnknownErr;
|
||||
|
||||
if (noErr == err)
|
||||
err = FSIsAliasFile(&fileRef, &aliasFileFlag, &folderFlag);
|
||||
|
||||
if (noErr == err)
|
||||
return (BOOL)(aliasFileFlag && folderFlag);
|
||||
else
|
||||
return NO;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,16 +0,0 @@
|
||||
//
|
||||
// NSFileManager+Authentication.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 3/9/06.
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef NSFILEMANAGER_PLUS_AUTHENTICATION_H
|
||||
#define NSFILEMANAGER_PLUS_AUTHENTICATION_H
|
||||
|
||||
@interface NSFileManager (SUAuthenticationAdditions)
|
||||
- (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst error:(NSError **)error;
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,249 +0,0 @@
|
||||
//
|
||||
// NSFileManager+Authentication.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 3/9/06.
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
// This code based on generous contribution from Allan Odgaard. Thanks, Allan!
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "NSFileManager+Authentication.h"
|
||||
|
||||
#import <Security/Security.h>
|
||||
#import <sys/stat.h>
|
||||
#import <sys/wait.h>
|
||||
#import <dirent.h>
|
||||
#import <unistd.h>
|
||||
|
||||
#import "NSFileManager+ExtendedAttributes.h"
|
||||
static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, const char* const* arguments)
|
||||
{
|
||||
sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL);
|
||||
BOOL returnValue = YES;
|
||||
|
||||
if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, (char* const*)arguments, NULL) == errAuthorizationSuccess)
|
||||
{
|
||||
int status;
|
||||
pid_t pid = wait(&status);
|
||||
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
|
||||
returnValue = NO;
|
||||
}
|
||||
else
|
||||
returnValue = NO;
|
||||
|
||||
signal(SIGCHLD, oldSigChildHandler);
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
@implementation NSFileManager (SUAuthenticationAdditions)
|
||||
|
||||
- (BOOL)currentUserOwnsPath:(NSString *)oPath
|
||||
{
|
||||
const char *path = [oPath fileSystemRepresentation];
|
||||
uid_t uid = getuid();
|
||||
bool res = false;
|
||||
struct stat sb;
|
||||
if(stat(path, &sb) == 0)
|
||||
{
|
||||
if(sb.st_uid == uid)
|
||||
{
|
||||
res = true;
|
||||
if(sb.st_mode & S_IFDIR)
|
||||
{
|
||||
DIR* dir = opendir(path);
|
||||
struct dirent* entry = NULL;
|
||||
while(res && (entry = readdir(dir)))
|
||||
{
|
||||
if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
|
||||
continue;
|
||||
|
||||
size_t len = strlen(path) + 1 + entry->d_namlen + 1;
|
||||
char descend[len];
|
||||
strlcpy(descend, path, len);
|
||||
strlcat(descend, "/", len);
|
||||
strlcat(descend, entry->d_name, len);
|
||||
NSString* newPath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:descend length:strlen(descend)];
|
||||
res = [self currentUserOwnsPath:newPath];
|
||||
}
|
||||
closedir(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
- (NSString *)_temporaryCopyNameForPath:(NSString *)path
|
||||
{
|
||||
// Let's try to read the version number so the filename will be more meaningful.
|
||||
NSString *postFix;
|
||||
NSBundle *bundle;
|
||||
if ((bundle = [NSBundle bundleWithPath:path]))
|
||||
{
|
||||
// We'll clean it up a little for safety.
|
||||
// The cast is necessary because of a bug in the headers in pre-10.5 SDKs
|
||||
NSMutableCharacterSet *validCharacters = (id)[NSMutableCharacterSet alphanumericCharacterSet];
|
||||
[validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]];
|
||||
postFix = [[bundle objectForInfoDictionaryKey:@"CFBundleVersion"] stringByTrimmingCharactersInSet:[validCharacters invertedSet]];
|
||||
}
|
||||
else
|
||||
postFix = @"old";
|
||||
NSString *prefix = [[path stringByDeletingPathExtension] stringByAppendingFormat:@" (%@)", postFix];
|
||||
NSString *tempDir = [prefix stringByAppendingPathExtension:[path pathExtension]];
|
||||
// Now let's make sure we get a unique path.
|
||||
int cnt=2;
|
||||
while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 999999)
|
||||
tempDir = [NSString stringWithFormat:@"%@ %d.%@", prefix, cnt++, [path pathExtension]];
|
||||
return tempDir;
|
||||
}
|
||||
|
||||
- (BOOL)_copyPathWithForcedAuthentication:(NSString *)src toPath:(NSString *)dst error:(NSError **)error
|
||||
{
|
||||
NSString *tmp = [self _temporaryCopyNameForPath:dst];
|
||||
const char* srcPath = [src fileSystemRepresentation];
|
||||
const char* tmpPath = [tmp fileSystemRepresentation];
|
||||
const char* dstPath = [dst fileSystemRepresentation];
|
||||
|
||||
struct stat dstSB;
|
||||
stat(dstPath, &dstSB);
|
||||
|
||||
AuthorizationRef auth = NULL;
|
||||
OSStatus authStat = errAuthorizationDenied;
|
||||
while (authStat == errAuthorizationDenied) {
|
||||
authStat = AuthorizationCreate(NULL,
|
||||
kAuthorizationEmptyEnvironment,
|
||||
kAuthorizationFlagDefaults,
|
||||
&auth);
|
||||
}
|
||||
|
||||
BOOL res = NO;
|
||||
if (authStat == errAuthorizationSuccess) {
|
||||
res = YES;
|
||||
|
||||
char uidgid[42];
|
||||
snprintf(uidgid, sizeof(uidgid), "%d:%d",
|
||||
dstSB.st_uid, dstSB.st_gid);
|
||||
|
||||
const char* executables[] = {
|
||||
"/bin/rm",
|
||||
"/bin/mv",
|
||||
"/bin/mv",
|
||||
"/bin/rm",
|
||||
NULL, // pause here and do some housekeeping before
|
||||
// continuing
|
||||
"/usr/sbin/chown",
|
||||
NULL // stop here for real
|
||||
};
|
||||
|
||||
// 4 is the maximum number of arguments to any command,
|
||||
// including the NULL that signals the end of an argument
|
||||
// list.
|
||||
const char* const argumentLists[][4] = {
|
||||
{ "-rf", tmpPath, NULL }, // make room for the temporary file... this is kinda unsafe; should probably do something better.
|
||||
{ "-f", dstPath, tmpPath, NULL }, // mv
|
||||
{ "-f", srcPath, dstPath, NULL }, // mv
|
||||
{ "-rf", tmpPath, NULL }, // rm
|
||||
{ NULL }, // pause
|
||||
{ "-R", uidgid, dstPath, NULL }, // chown
|
||||
{ NULL } // stop
|
||||
};
|
||||
|
||||
// Process the commands up until the first NULL
|
||||
int commandIndex = 0;
|
||||
for (; executables[commandIndex] != NULL; ++commandIndex) {
|
||||
if (res)
|
||||
res = AuthorizationExecuteWithPrivilegesAndWait(auth, executables[commandIndex], kAuthorizationFlagDefaults, argumentLists[commandIndex]);
|
||||
}
|
||||
|
||||
// If the currently-running application is trusted, the new
|
||||
// version should be trusted as well. Remove it from the
|
||||
// quarantine to avoid a delay at launch, and to avoid
|
||||
// presenting the user with a confusing trust dialog.
|
||||
//
|
||||
// This needs to be done after the application is moved to its
|
||||
// new home with "mv" in case it's moved across filesystems: if
|
||||
// that happens, "mv" actually performs a copy and may result
|
||||
// in the application being quarantined. It also needs to be
|
||||
// done before "chown" changes ownership, because the ownership
|
||||
// change will almost certainly make it impossible to change
|
||||
// attributes to release the files from the quarantine.
|
||||
if (res) {
|
||||
[self releaseFromQuarantine:dst];
|
||||
}
|
||||
|
||||
// Now move past the NULL we found and continue executing
|
||||
// commands from the list.
|
||||
++commandIndex;
|
||||
|
||||
for (; executables[commandIndex] != NULL; ++commandIndex) {
|
||||
if (res)
|
||||
res = AuthorizationExecuteWithPrivilegesAndWait(auth, executables[commandIndex], kAuthorizationFlagDefaults, argumentLists[commandIndex]);
|
||||
}
|
||||
|
||||
AuthorizationFree(auth, 0);
|
||||
|
||||
if (!res)
|
||||
{
|
||||
// Something went wrong somewhere along the way, but we're not sure exactly where.
|
||||
NSString *errorMessage = [NSString stringWithFormat:@"Authenticated file copy from %@ to %@ failed.", src, dst];
|
||||
if (error != NULL)
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (error != NULL)
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:[NSDictionary dictionaryWithObject:@"Couldn't get permission to authenticate." forKey:NSLocalizedDescriptionKey]];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
- (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst error:(NSError **)error
|
||||
{
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:dst])
|
||||
{
|
||||
NSString *errorMessage = [NSString stringWithFormat:@"Couldn't copy %@ over %@ because there is no file at %@.", src, dst, dst];
|
||||
if (error != NULL)
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (![[NSFileManager defaultManager] isWritableFileAtPath:dst] || ![[NSFileManager defaultManager] isWritableFileAtPath:[dst stringByDeletingLastPathComponent]])
|
||||
return [self _copyPathWithForcedAuthentication:src toPath:dst error:error];
|
||||
|
||||
NSString *tmpPath = [self _temporaryCopyNameForPath:dst];
|
||||
|
||||
if (![[NSFileManager defaultManager] movePath:dst toPath:tmpPath handler:self])
|
||||
{
|
||||
if (error != NULL)
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] forKey:NSLocalizedDescriptionKey]];
|
||||
return NO;
|
||||
}
|
||||
if (![[NSFileManager defaultManager] copyPath:src toPath:dst handler:self])
|
||||
{
|
||||
if (error != NULL)
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't copy %@ to %@.", src, dst] forKey:NSLocalizedDescriptionKey]];
|
||||
return NO;
|
||||
}
|
||||
|
||||
// Trash the old copy of the app.
|
||||
NSInteger tag = 0;
|
||||
if (![[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[tmpPath stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[tmpPath lastPathComponent]] tag:&tag])
|
||||
NSLog(@"Sparkle error: couldn't move %@ to the trash. This is often a sign of a permissions error.", tmpPath);
|
||||
|
||||
// If the currently-running application is trusted, the new
|
||||
// version should be trusted as well. Remove it from the
|
||||
// quarantine to avoid a delay at launch, and to avoid
|
||||
// presenting the user with a confusing trust dialog.
|
||||
//
|
||||
// This needs to be done after the application is moved to its
|
||||
// new home in case it's moved across filesystems: if that
|
||||
// happens, the move is actually a copy, and it may result
|
||||
// in the application being quarantined.
|
||||
[self releaseFromQuarantine:dst];
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,53 +0,0 @@
|
||||
//
|
||||
// NSFileManager+ExtendedAttributes.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mark Mentovai on 2008-01-22.
|
||||
// Copyright 2008 Mark Mentovai. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef NSFILEMANAGER_PLUS_EXTENDEDATTRIBUTES
|
||||
#define NSFILEMANAGER_PLUS_EXTENDEDATTRIBUTES
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@interface NSFileManager (MMExtendedAttributes)
|
||||
|
||||
// Wraps the removexattr system call, allowing an AppKit-style NSString* to
|
||||
// be used for the pathname argument. Note that the order of the arguments
|
||||
// has changed from what removexattr accepts, so that code reads more
|
||||
// naturally.
|
||||
//
|
||||
// removexattr is only available on Mac OS X 10.4 ("Tiger") and later. If
|
||||
// built with an SDK that includes removexattr, this method will link against
|
||||
// removexattr directly. When using earlier SDKs, this method will dynamically
|
||||
// look up the removexattr symbol at runtime. If the symbol is not present,
|
||||
// as will be the case when running on 10.3, this method returns -1 and sets
|
||||
// errno to ENOSYS.
|
||||
- (int)removeXAttr:(const char*)name
|
||||
fromFile:(NSString*)file
|
||||
options:(int)options;
|
||||
|
||||
// Removes the directory tree rooted at |root| from the file quarantine.
|
||||
// The quarantine was introduced on Mac OS X 10.5 and is described at:
|
||||
//
|
||||
// http://developer.apple.com/releasenotes/Carbon/RN-LaunchServices/index.html
|
||||
//#apple_ref/doc/uid/TP40001369-DontLinkElementID_2
|
||||
//
|
||||
// If |root| is not a directory, then it alone is removed from the quarantine.
|
||||
// Symbolic links, including |root| if it is a symbolic link, will not be
|
||||
// traversed.
|
||||
//
|
||||
// Ordinarily, the quarantine is managed by calling LSSetItemAttribute
|
||||
// to set the kLSItemQuarantineProperties attribute to a dictionary specifying
|
||||
// the quarantine properties to be applied. However, it does not appear to be
|
||||
// possible to remove an item from the quarantine directly through any public
|
||||
// Launch Services calls. Instead, this method takes advantage of the fact
|
||||
// that the quarantine is implemented in part by setting an extended attribute,
|
||||
// "com.apple.quarantine", on affected files. Removing this attribute is
|
||||
// sufficient to remove files from the quarantine.
|
||||
- (void)releaseFromQuarantine:(NSString*)root;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,98 +0,0 @@
|
||||
//
|
||||
// NSFileManager+ExtendedAttributes.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mark Mentovai on 2008-01-22.
|
||||
// Copyright 2008 Mark Mentovai. All rights reserved.
|
||||
//
|
||||
|
||||
#import "NSFileManager+ExtendedAttributes.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
|
||||
// Extended attribute support was introduced in Mac OS X 10.4 ("Tiger").
|
||||
// If building with an earlier SDK, provide definitions needed to handle
|
||||
// extended attributes at runtime.
|
||||
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 // SDK >= 10.4
|
||||
#include <sys/xattr.h>
|
||||
#else // SDK >= 10.4
|
||||
#define XATTR_NOFOLLOW 1
|
||||
#endif // SDK >= 10.4
|
||||
|
||||
@implementation NSFileManager (MMExtendedAttributes)
|
||||
|
||||
- (int)removeXAttr:(const char*)name
|
||||
fromFile:(NSString*)file
|
||||
options:(int)options
|
||||
{
|
||||
typedef int (*removexattr_type)(const char*, const char*, int);
|
||||
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 // SDK >= 10.4
|
||||
// Reference removexattr directly, it's in the SDK.
|
||||
static removexattr_type removexattr_func = removexattr;
|
||||
#else // SDK >= 10.4
|
||||
// removexattr isn't in this SDK, look it up at runtime.
|
||||
static removexattr_type removexattr_func = NULL;
|
||||
static BOOL didSymbolLookup = NO;
|
||||
if (!didSymbolLookup) {
|
||||
didSymbolLookup = YES;
|
||||
removexattr_func = dlsym(RTLD_NEXT, "removexattr");
|
||||
}
|
||||
#endif // SDK >= 10.4
|
||||
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4 // DT < 10.4
|
||||
// Make sure that the symbol is present. This checks the deployment
|
||||
// target instead of the SDK so that it's able to catch dlsym failures
|
||||
// as well as the null symbol that would result from building with the
|
||||
// 10.4 SDK and a lower deployment target, and running on 10.3.
|
||||
if (!removexattr_func) {
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
#endif // DT < 10.4
|
||||
|
||||
const char* path = NULL;
|
||||
@try {
|
||||
path = [file fileSystemRepresentation];
|
||||
}
|
||||
@catch (id exception) {
|
||||
// -[NSString fileSystemRepresentation] throws an exception if it's
|
||||
// unable to convert the string to something suitable. Map that to
|
||||
// EDOM, "argument out of domain", which sort of conveys that there
|
||||
// was a conversion failure.
|
||||
errno = EDOM;
|
||||
return -1;
|
||||
}
|
||||
|
||||
return removexattr_func(path, name, options);
|
||||
}
|
||||
|
||||
- (void)releaseFromQuarantine:(NSString*)root
|
||||
{
|
||||
const char* quarantineAttribute = "com.apple.quarantine";
|
||||
const int removeXAttrOptions = XATTR_NOFOLLOW;
|
||||
|
||||
[self removeXAttr:quarantineAttribute
|
||||
fromFile:root
|
||||
options:removeXAttrOptions];
|
||||
|
||||
// Only recurse if it's actually a directory. Don't recurse into a
|
||||
// root-level symbolic link.
|
||||
NSDictionary* rootAttributes =
|
||||
[self fileAttributesAtPath:root traverseLink:NO];
|
||||
NSString* rootType = [rootAttributes objectForKey:NSFileType];
|
||||
|
||||
if (rootType == NSFileTypeDirectory) {
|
||||
// The NSDirectoryEnumerator will avoid recursing into any contained
|
||||
// symbolic links, so no further type checks are needed.
|
||||
NSDirectoryEnumerator* directoryEnumerator = [self enumeratorAtPath:root];
|
||||
NSString* file = nil;
|
||||
while ((file = [directoryEnumerator nextObject])) {
|
||||
[self removeXAttr:quarantineAttribute
|
||||
fromFile:[root stringByAppendingPathComponent:file]
|
||||
options:removeXAttrOptions];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,17 +0,0 @@
|
||||
//
|
||||
// NSFileManager+Verification.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 3/16/06.
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef NSFILEMANAGER_PLUS_VERIFICATION_H
|
||||
#define NSFILEMANAGER_PLUS_VERIFICATION_H
|
||||
|
||||
// For the paranoid folks!
|
||||
@interface NSFileManager (SUVerification)
|
||||
- (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString;
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,151 +0,0 @@
|
||||
//
|
||||
// NSFileManager+Verification.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 3/16/06.
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
// DSA stuff adapted from code provided by Allan Odgaard. Thanks, Allan!
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "NSFileManager+Verification.h"
|
||||
|
||||
#import <stdio.h>
|
||||
#import <openssl/evp.h>
|
||||
#import <openssl/bio.h>
|
||||
#import <openssl/pem.h>
|
||||
#import <openssl/rsa.h>
|
||||
#import <openssl/sha.h>
|
||||
|
||||
long b64decode(unsigned char* str)
|
||||
{
|
||||
unsigned char *cur, *start;
|
||||
int d, dlast, phase;
|
||||
unsigned char c;
|
||||
static int table[256] = {
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 00-0F */
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 10-1F */
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, /* 20-2F */
|
||||
52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, /* 30-3F */
|
||||
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 40-4F */
|
||||
15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* 50-5F */
|
||||
-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* 60-6F */
|
||||
41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, /* 70-7F */
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 80-8F */
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 90-9F */
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* A0-AF */
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* B0-BF */
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* C0-CF */
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* D0-DF */
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* E0-EF */
|
||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 /* F0-FF */
|
||||
};
|
||||
|
||||
d = dlast = phase = 0;
|
||||
start = str;
|
||||
for (cur = str; *cur != '\0'; ++cur )
|
||||
{
|
||||
if(*cur == '\n' || *cur == '\r'){phase = dlast = 0; continue;}
|
||||
d = table[(int)*cur];
|
||||
if(d != -1)
|
||||
{
|
||||
switch(phase)
|
||||
{
|
||||
case 0:
|
||||
++phase;
|
||||
break;
|
||||
case 1:
|
||||
c = ((dlast << 2) | ((d & 0x30) >> 4));
|
||||
*str++ = c;
|
||||
++phase;
|
||||
break;
|
||||
case 2:
|
||||
c = (((dlast & 0xf) << 4) | ((d & 0x3c) >> 2));
|
||||
*str++ = c;
|
||||
++phase;
|
||||
break;
|
||||
case 3:
|
||||
c = (((dlast & 0x03 ) << 6) | d);
|
||||
*str++ = c;
|
||||
phase = 0;
|
||||
break;
|
||||
}
|
||||
dlast = d;
|
||||
}
|
||||
}
|
||||
*str = '\0';
|
||||
return str - start;
|
||||
}
|
||||
|
||||
EVP_PKEY* load_dsa_key(char *key)
|
||||
{
|
||||
EVP_PKEY* pkey = NULL;
|
||||
BIO *bio;
|
||||
if((bio = BIO_new_mem_buf(key, (int)strlen(key))))
|
||||
{
|
||||
DSA* dsa_key = 0;
|
||||
if(PEM_read_bio_DSA_PUBKEY(bio, &dsa_key, NULL, NULL))
|
||||
{
|
||||
if((pkey = EVP_PKEY_new()))
|
||||
{
|
||||
if(EVP_PKEY_assign_DSA(pkey, dsa_key) != 1)
|
||||
{
|
||||
DSA_free(dsa_key);
|
||||
EVP_PKEY_free(pkey);
|
||||
pkey = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
BIO_free(bio);
|
||||
}
|
||||
return pkey;
|
||||
}
|
||||
|
||||
@implementation NSFileManager (SUVerification)
|
||||
|
||||
- (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString
|
||||
{
|
||||
BOOL result = NO;
|
||||
if (!encodedSignature) { return NO; }
|
||||
if (!pkeyString) { return NO; }
|
||||
|
||||
// Remove whitespace around each line of the key.
|
||||
NSMutableArray *pkeyTrimmedLines = [NSMutableArray array];
|
||||
NSEnumerator *pkeyLinesEnumerator = [[pkeyString componentsSeparatedByString:@"\n"] objectEnumerator];
|
||||
NSString *pkeyLine;
|
||||
while ((pkeyLine = [pkeyLinesEnumerator nextObject]) != nil)
|
||||
{
|
||||
[pkeyTrimmedLines addObject:[pkeyLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
|
||||
}
|
||||
pkeyString = [pkeyTrimmedLines componentsJoinedByString:@"\n"]; // Put them back together.
|
||||
|
||||
EVP_PKEY* pkey = NULL;
|
||||
pkey = load_dsa_key((char *)[pkeyString UTF8String]);
|
||||
if (!pkey) { return NO; }
|
||||
|
||||
// Now, the signature is in base64; we have to decode it into a binary stream.
|
||||
unsigned char *signature = (unsigned char *)[encodedSignature UTF8String];
|
||||
long length = b64decode(signature); // Decode the signature in-place and get the new length of the signature string.
|
||||
|
||||
// We've got the signature, now get the file data.
|
||||
NSData *pathData = [NSData dataWithContentsOfFile:path];
|
||||
if (!pathData) { return NO; }
|
||||
|
||||
// Hash the file with SHA-1.
|
||||
unsigned char md[SHA_DIGEST_LENGTH];
|
||||
SHA1([pathData bytes], [pathData length], md);
|
||||
|
||||
// Actually verify the signature on the file.
|
||||
EVP_MD_CTX ctx;
|
||||
if(EVP_VerifyInit(&ctx, EVP_dss1()) == 1) // We're using DSA keys.
|
||||
{
|
||||
EVP_VerifyUpdate(&ctx, md, SHA_DIGEST_LENGTH);
|
||||
result = (EVP_VerifyFinal(&ctx, signature, (unsigned int)length, pkey) == 1);
|
||||
}
|
||||
|
||||
EVP_PKEY_free(pkey);
|
||||
return result;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,16 +0,0 @@
|
||||
//
|
||||
// NSNumber+Units.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Jonas Witt on 5/18/08.
|
||||
// Copyright 2008 __MyCompanyName__. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
|
||||
@interface NSNumber (JWUnits)
|
||||
|
||||
+ (NSString *)humanReadableSizeFromDouble:(double)value;
|
||||
|
||||
@end
|
||||
@@ -1,28 +0,0 @@
|
||||
//
|
||||
// NSNumber+Units.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Jonas Witt on 5/18/08.
|
||||
// Copyright 2008 __MyCompanyName__. All rights reserved.
|
||||
//
|
||||
|
||||
#import "NSNumber+Units.h"
|
||||
#import "Sparkle.h"
|
||||
|
||||
@implementation NSNumber (JWUnits)
|
||||
|
||||
+ (NSString *)humanReadableSizeFromDouble:(double)value
|
||||
{
|
||||
if (value < 1024)
|
||||
return [NSString stringWithFormat:@"%.0lf %@", value, SULocalizedString(@"B", @"the unit for bytes")];
|
||||
|
||||
if (value < 1024 * 1024)
|
||||
return [NSString stringWithFormat:@"%.0lf %@", value / 1024.0, SULocalizedString(@"KB", @"the unit for kilobytes")];
|
||||
|
||||
if (value < 1024 * 1024 * 1024)
|
||||
return [NSString stringWithFormat:@"%.1lf %@", value / 1024.0 / 1024.0, SULocalizedString(@"MB", @"the unit for megabytes")];
|
||||
|
||||
return [NSString stringWithFormat:@"%.2lf %@", value / 1024.0 / 1024.0 / 1024.0, SULocalizedString(@"GB", @"the unit for gigabytes")];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,66 +0,0 @@
|
||||
/*
|
||||
|
||||
BSD License
|
||||
|
||||
Copyright (c) 2002, Brent Simmons
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of ranchero.com or Brent Simmons nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
|
||||
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
|
||||
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
|
||||
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
*/
|
||||
|
||||
#ifndef NSSTRING_PLUS_EXTRAS_H
|
||||
#define NSSTRING_PLUS_EXTRAS_H
|
||||
|
||||
|
||||
/*
|
||||
NSString+extras.h
|
||||
NetNewsWire
|
||||
|
||||
Created by Brent Simmons on Fri Jun 14 2002.
|
||||
Copyright (c) 2002 Brent Simmons. All rights reserved.
|
||||
*/
|
||||
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <CoreFoundation/CoreFoundation.h>
|
||||
#import "SUConstants.h" // for NSInteger
|
||||
|
||||
@interface NSString (BSextras)
|
||||
|
||||
- (NSString *)stringWithSubstitute:(NSString *)subs forCharactersFromSet:(NSCharacterSet *)set;
|
||||
|
||||
- (NSString *) trimWhiteSpace;
|
||||
|
||||
- (NSString *) stripHTML;
|
||||
|
||||
- (NSString *) ellipsizeAfterNWords: (NSInteger) n;
|
||||
|
||||
+ (BOOL) stringIsEmpty: (NSString *) s;
|
||||
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,136 +0,0 @@
|
||||
/*
|
||||
|
||||
BSD License
|
||||
|
||||
Copyright (c) 2002, Brent Simmons
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of ranchero.com or Brent Simmons nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
|
||||
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
|
||||
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
|
||||
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
NSString+extras.m
|
||||
NetNewsWire
|
||||
|
||||
Created by Brent Simmons on Fri Jun 14 2002.
|
||||
Copyright (c) 2002 Brent Simmons. All rights reserved.
|
||||
*/
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "NSString+extras.h"
|
||||
|
||||
|
||||
@implementation NSString (BSextras)
|
||||
|
||||
- (NSString *)stringWithSubstitute:(NSString *)subs forCharactersFromSet:(NSCharacterSet *)set
|
||||
{
|
||||
NSRange r = [self rangeOfCharacterFromSet:set];
|
||||
if (r.location == NSNotFound) return self;
|
||||
NSMutableString *newString = [self mutableCopy];
|
||||
do
|
||||
{
|
||||
[newString replaceCharactersInRange:r withString:subs];
|
||||
r = [newString rangeOfCharacterFromSet:set];
|
||||
}
|
||||
while (r.location != NSNotFound);
|
||||
return [newString autorelease];
|
||||
}
|
||||
|
||||
- (NSString *) trimWhiteSpace {
|
||||
|
||||
NSMutableString *s = [[self mutableCopy] autorelease];
|
||||
|
||||
CFStringTrimWhitespace ((CFMutableStringRef) s);
|
||||
|
||||
return (NSString *) [[s copy] autorelease];
|
||||
} /*trimWhiteSpace*/
|
||||
|
||||
|
||||
- (NSString *) ellipsizeAfterNWords: (NSInteger) n {
|
||||
|
||||
NSArray *stringComponents = [self componentsSeparatedByString: @" "];
|
||||
NSMutableArray *componentsCopy = [stringComponents mutableCopy];
|
||||
NSInteger ix = n;
|
||||
NSInteger len = [componentsCopy count];
|
||||
|
||||
if (len < n)
|
||||
ix = len;
|
||||
|
||||
[componentsCopy removeObjectsInRange: NSMakeRange (ix, len - ix)];
|
||||
|
||||
return [componentsCopy componentsJoinedByString: @" "];
|
||||
} /*ellipsizeAfterNWords*/
|
||||
|
||||
|
||||
- (NSString *) stripHTML {
|
||||
|
||||
NSUInteger len = [self length];
|
||||
NSMutableString *s = [NSMutableString stringWithCapacity: len];
|
||||
NSUInteger i = 0, level = 0;
|
||||
|
||||
for (i = 0; i < len; i++) {
|
||||
|
||||
NSString *ch = [self substringWithRange: NSMakeRange (i, 1)];
|
||||
|
||||
if ([ch isEqualTo: @"<"])
|
||||
level++;
|
||||
|
||||
else if ([ch isEqualTo: @">"]) {
|
||||
|
||||
level--;
|
||||
|
||||
if (level == 0)
|
||||
[s appendString: @" "];
|
||||
} /*else if*/
|
||||
|
||||
else if (level == 0)
|
||||
[s appendString: ch];
|
||||
} /*for*/
|
||||
|
||||
return (NSString *) [[s copy] autorelease];
|
||||
} /*stripHTML*/
|
||||
|
||||
|
||||
+ (BOOL) stringIsEmpty: (NSString *) s {
|
||||
|
||||
NSString *copy;
|
||||
|
||||
if (s == nil)
|
||||
return (YES);
|
||||
|
||||
if ([s isEqualTo: @""])
|
||||
return (YES);
|
||||
|
||||
copy = [[s copy] autorelease];
|
||||
|
||||
if ([[copy trimWhiteSpace] isEqualTo: @""])
|
||||
return (YES);
|
||||
|
||||
return (NO);
|
||||
} /*stringIsEmpty*/
|
||||
|
||||
@end
|
||||
@@ -1,18 +0,0 @@
|
||||
//
|
||||
// NSURL+Parameters.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 5/6/08.
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef NSURL_PLUS_PARAMETERS_H
|
||||
#define NSURL_PLUS_PARAMETERS_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@interface NSURL (SUParameterAdditions)
|
||||
- (NSURL *)URLWithParameters:(NSArray *)parameters;
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,27 +0,0 @@
|
||||
//
|
||||
// NSURL+Parameters.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 5/6/08.
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "NSURL+Parameters.h"
|
||||
|
||||
@implementation NSURL (SUParameterAdditions)
|
||||
- (NSURL *)URLWithParameters:(NSArray *)parameters;
|
||||
{
|
||||
if (parameters == nil || [parameters count] == 0) { return self; }
|
||||
NSMutableArray *profileInfo = [NSMutableArray array];
|
||||
NSEnumerator *profileInfoEnumerator = [parameters objectEnumerator];
|
||||
NSDictionary *currentProfileInfo;
|
||||
while ((currentProfileInfo = [profileInfoEnumerator nextObject])) {
|
||||
[profileInfo addObject:[NSString stringWithFormat:@"%@=%@", [currentProfileInfo objectForKey:@"key"], [currentProfileInfo objectForKey:@"value"]]];
|
||||
}
|
||||
|
||||
NSString *appcastStringWithProfile = [NSString stringWithFormat:@"%@?%@", [self absoluteString], [profileInfo componentsJoinedByString:@"&"]];
|
||||
|
||||
// Clean it up so it's a valid URL
|
||||
return [NSURL URLWithString:[appcastStringWithProfile stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
|
||||
}
|
||||
@end
|
||||
@@ -1,18 +0,0 @@
|
||||
//
|
||||
// NSWorkspace+SystemVersion.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 5/7/08.
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef NSWORKSPACE_PLUS_SYSTEMVERSION_H
|
||||
#define NSWORKSPACE_PLUS_SYSTEMVERSION_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@interface NSWorkspace (SUSystemVersion)
|
||||
+ (NSString *)systemVersionString;
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,36 +0,0 @@
|
||||
//
|
||||
// NSWorkspace+SystemVersion.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 5/7/08.
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "NSWorkspace+SystemVersion.h"
|
||||
|
||||
|
||||
@implementation NSWorkspace (SUSystemVersion)
|
||||
+ (NSString *)systemVersionString
|
||||
{
|
||||
// This returns a version string of the form X.Y.Z
|
||||
// There may be a better way to deal with the problem that gestaltSystemVersionMajor
|
||||
// et al. are not defined in 10.3, but this is probably good enough.
|
||||
NSString* verStr = nil;
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4
|
||||
SInt32 major, minor, bugfix;
|
||||
OSErr err1 = Gestalt(gestaltSystemVersionMajor, &major);
|
||||
OSErr err2 = Gestalt(gestaltSystemVersionMinor, &minor);
|
||||
OSErr err3 = Gestalt(gestaltSystemVersionBugFix, &bugfix);
|
||||
if (!err1 && !err2 && !err3)
|
||||
{
|
||||
verStr = [NSString stringWithFormat:@"%d.%d.%d", major, minor, bugfix];
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
NSString *versionPlistPath = @"/System/Library/CoreServices/SystemVersion.plist";
|
||||
verStr = [[[NSDictionary dictionaryWithContentsOfFile:versionPlistPath] objectForKey:@"ProductVersion"] retain];
|
||||
}
|
||||
return verStr;
|
||||
}
|
||||
@end
|
||||
@@ -1,41 +0,0 @@
|
||||
//
|
||||
// NSWorkspace_RBAdditions.h
|
||||
// PathProps
|
||||
//
|
||||
// Created by Rainer Brockerhoff on 10/04/2007.
|
||||
// Copyright 2007 Rainer Brockerhoff. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef NSWORKSPACE_RBADDITIONS_H
|
||||
#define NSWORKSPACE_RBADDITIONS_H
|
||||
|
||||
|
||||
extern NSString* NSWorkspace_RBfstypename;
|
||||
extern NSString* NSWorkspace_RBmntonname;
|
||||
extern NSString* NSWorkspace_RBmntfromname;
|
||||
extern NSString* NSWorkspace_RBdeviceinfo;
|
||||
extern NSString* NSWorkspace_RBimagefilepath;
|
||||
extern NSString* NSWorkspace_RBconnectiontype;
|
||||
extern NSString* NSWorkspace_RBpartitionscheme;
|
||||
extern NSString* NSWorkspace_RBserverURL;
|
||||
|
||||
@interface NSWorkspace (NSWorkspace_RBAdditions)
|
||||
|
||||
// This method will return nil if the input path is invalid. Otherwise, the returned NSDictionary may contain
|
||||
// the following keys:
|
||||
//- NSWorkspace_RBfstypename: will always be present.Shows the filesystem type (usually "hfs"), from statfs.
|
||||
//- NSWorkspace_RBmntonname: will always be present. Shows the volume mount point.
|
||||
//- NSWorkspace_RBmntfromname: will always be present. Shows the BSD device path for local volumes; info for
|
||||
// remote volumes depends on the filesystem type.
|
||||
//- NSWorkspace_RBconnectiontype: should always be present for local volumes. Shows the connection type ("SATA", "USB", etc.).
|
||||
//- NSWorkspace_RBpartitionscheme: should always be present for local volumes. Shows the partition scheme.
|
||||
//- NSWorkspace_RBdeviceinfo: should always be present for local volumes. Shows some information about the
|
||||
// physical device; varies widely.
|
||||
//- NSWorkspace_RBimagefilepath: should be present for disk images only. Shows the path of the disk image file.
|
||||
//- NSWorkspace_RBserverURL: should be present for remote volumes only. Shows the server URL.
|
||||
|
||||
- (NSDictionary*)propertiesForPath:(NSString*)path;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,177 +0,0 @@
|
||||
//
|
||||
// NSWorkspace_RBAdditions.m
|
||||
// PathProps
|
||||
//
|
||||
// Created by Rainer Brockerhoff on 10/04/2007.
|
||||
// Copyright 2007 Rainer Brockerhoff. All rights reserved.
|
||||
//
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "NSWorkspace_RBAdditions.h"
|
||||
|
||||
#include <IOKit/IOKitLib.h>
|
||||
#include <sys/mount.h>
|
||||
#include <mach/mach.h>
|
||||
|
||||
NSString* NSWorkspace_RBfstypename = @"NSWorkspace_RBfstypename";
|
||||
NSString* NSWorkspace_RBmntonname = @"NSWorkspace_RBmntonname";
|
||||
NSString* NSWorkspace_RBmntfromname = @"NSWorkspace_RBmntfromname";
|
||||
NSString* NSWorkspace_RBdeviceinfo = @"NSWorkspace_RBdeviceinfo";
|
||||
NSString* NSWorkspace_RBimagefilepath = @"NSWorkspace_RBimagefilepath";
|
||||
NSString* NSWorkspace_RBconnectiontype = @"NSWorkspace_RBconnectiontype";
|
||||
NSString* NSWorkspace_RBpartitionscheme = @"NSWorkspace_RBpartitionscheme";
|
||||
NSString* NSWorkspace_RBserverURL = @"NSWorkspace_RBserverURL";
|
||||
|
||||
// This static funtion concatenates two strings, but first checks several possibilities...
|
||||
// like one or the other nil, or one containing the other already.
|
||||
|
||||
static NSString* AddPart(NSString* first,NSString* second) {
|
||||
if (!second) {
|
||||
return first;
|
||||
}
|
||||
second = [second stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
|
||||
if (first) {
|
||||
if ([first rangeOfString:second options:NSCaseInsensitiveSearch].location==NSNotFound) {
|
||||
if ([second rangeOfString:first options:NSCaseInsensitiveSearch].location==NSNotFound) {
|
||||
return [NSString stringWithFormat:@"%@; %@",first,second];
|
||||
}
|
||||
return second;
|
||||
}
|
||||
return first;
|
||||
}
|
||||
return second;
|
||||
}
|
||||
|
||||
// This static functions recurses "upwards" over the IO registry. Returns strings that are concatenated
|
||||
// and ultimately end up under the NSWorkspace_RBdeviceinfo key.
|
||||
// This isn't too robust in that it assumes that objects returned by the objectForKey methods are
|
||||
// either strings or dictionaries. A "standard" implementations would use either only CoreFoundation and
|
||||
// IOKit calls for this, or do more robust type checking on the returned objects.
|
||||
//
|
||||
// Also notice that this works as determined experimentally in 10.4.9, there's no official docs I could find.
|
||||
// YMMV, and it may stop working in any new version of Mac OS X.
|
||||
|
||||
static NSString* CheckParents(io_object_t thing,NSString* part,NSMutableDictionary* dict) {
|
||||
NSString* result = part;
|
||||
io_iterator_t parentsIterator = 0;
|
||||
kern_return_t kernResult = IORegistryEntryGetParentIterator(thing,kIOServicePlane,&parentsIterator);
|
||||
if ((kernResult==KERN_SUCCESS)&&parentsIterator) {
|
||||
io_object_t nextParent = 0;
|
||||
while ((nextParent = IOIteratorNext(parentsIterator))) {
|
||||
NSDictionary* props = nil;
|
||||
NSString* image = nil;
|
||||
NSString* partition = nil;
|
||||
NSString* connection = nil;
|
||||
kernResult = IORegistryEntryCreateCFProperties(nextParent,(CFMutableDictionaryRef*)&props,kCFAllocatorDefault,0);
|
||||
if (IOObjectConformsTo(nextParent,"IOApplePartitionScheme")) {
|
||||
partition = [props objectForKey:@"Content Mask"];
|
||||
} else if (IOObjectConformsTo(nextParent,"IOMedia")) {
|
||||
partition = [props objectForKey:@"Content"];
|
||||
} else if (IOObjectConformsTo(nextParent,"IODiskImageBlockStorageDeviceOutKernel")) {
|
||||
NSData* data = nil;
|
||||
if ((data = [[props objectForKey:@"Protocol Characteristics"] objectForKey:@"Virtual Interface Location Path"])) {
|
||||
image = [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding] autorelease];
|
||||
}
|
||||
} else if (IOObjectConformsTo(nextParent,"IOHDIXHDDriveInKernel")) {
|
||||
image = [props objectForKey:@"KDIURLPath"];
|
||||
}
|
||||
NSDictionary* subdict;
|
||||
if ((subdict = [props objectForKey:@"Protocol Characteristics"])) {
|
||||
connection = [subdict objectForKey:@"Physical Interconnect"];
|
||||
} else {
|
||||
connection = [props objectForKey:@"Physical Interconnect"];
|
||||
}
|
||||
if (connection) {
|
||||
[dict setObject:AddPart([dict objectForKey:NSWorkspace_RBconnectiontype],connection) forKey:NSWorkspace_RBconnectiontype];
|
||||
}
|
||||
if (partition) {
|
||||
[dict setObject:partition forKey:NSWorkspace_RBpartitionscheme];
|
||||
}
|
||||
if (image) {
|
||||
[dict setObject:image forKey:NSWorkspace_RBimagefilepath];
|
||||
}
|
||||
NSString* value;
|
||||
if ((subdict = [props objectForKey:@"Device Characteristics"])) {
|
||||
if ((value = [subdict objectForKey:@"Product Name"])) {
|
||||
result = AddPart(result,value);
|
||||
}
|
||||
if ((value = [subdict objectForKey:@"Product Revision Level"])) {
|
||||
result = AddPart(result,value);
|
||||
}
|
||||
if ((value = [subdict objectForKey:@"Vendor Name"])) {
|
||||
result = AddPart(result,value);
|
||||
}
|
||||
}
|
||||
if ((value = [props objectForKey:@"USB Serial Number"])) {
|
||||
result = AddPart(result,value);
|
||||
}
|
||||
if ((value = [props objectForKey:@"USB Vendor Name"])) {
|
||||
result = AddPart(result,value);
|
||||
}
|
||||
io_name_t ts; // char[128]
|
||||
NSString* cls = ( IOObjectGetClass (nextParent, ts) == KERN_SUCCESS ) ? [NSString stringWithUTF8String:ts ] : nil;
|
||||
if (![cls isEqualToString:@"IOPCIDevice"]) {
|
||||
|
||||
// Uncomment the following line to have the device tree dumped to the console.
|
||||
// NSLog(@"=================================> %@:%@\n",cls,props);
|
||||
|
||||
result = CheckParents(nextParent,result,dict);
|
||||
}
|
||||
if (props) { CFRelease(props); }
|
||||
IOObjectRelease(nextParent);
|
||||
}
|
||||
}
|
||||
if (parentsIterator) {
|
||||
IOObjectRelease(parentsIterator);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@implementation NSWorkspace (NSWorkspace_RBAdditions)
|
||||
|
||||
// Returns a NSDictionary with properties for the path. See details in the .h file.
|
||||
// This assumes that the length of path is less than PATH_MAX (currently 1024 characters).
|
||||
|
||||
- (NSDictionary*)propertiesForPath:(NSString*)path {
|
||||
const char* ccpath = [path fileSystemRepresentation];
|
||||
NSMutableDictionary* result = nil;
|
||||
struct statfs fs = {};
|
||||
if (!statfs(ccpath,&fs)) {
|
||||
NSString* from = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:fs.f_mntfromname length:strlen(fs.f_mntfromname)];
|
||||
result = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithUTF8String:fs.f_fstypename], NSWorkspace_RBfstypename, [[NSFileManager defaultManager] stringWithFileSystemRepresentation:fs.f_mntonname length:strlen(fs.f_mntonname)], NSWorkspace_RBmntonname, nil];
|
||||
const char* devstring = "/dev/";
|
||||
size_t devstringlen = 5;
|
||||
if (strncmp(fs.f_mntfromname,devstring,devstringlen)==0) {
|
||||
// For a local volume,get the IO registry tree and search it for further info.
|
||||
mach_port_t masterPort = 0;
|
||||
io_iterator_t mediaIterator = 0;
|
||||
kern_return_t kernResult = IOMasterPort(bootstrap_port,&masterPort);
|
||||
if (kernResult==KERN_SUCCESS) {
|
||||
CFMutableDictionaryRef classesToMatch = IOBSDNameMatching(masterPort,0,&fs.f_mntfromname[devstringlen]);
|
||||
if (classesToMatch) {
|
||||
kernResult = IOServiceGetMatchingServices(masterPort,classesToMatch,&mediaIterator);
|
||||
if ((kernResult==KERN_SUCCESS)&&mediaIterator) {
|
||||
io_object_t firstMedia = 0;
|
||||
while ((firstMedia = IOIteratorNext(mediaIterator))) {
|
||||
NSString* stuff = CheckParents(firstMedia,nil,result);
|
||||
if (stuff) {
|
||||
[result setObject:stuff forKey:NSWorkspace_RBdeviceinfo];
|
||||
}
|
||||
IOObjectRelease(firstMedia);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (mediaIterator) {
|
||||
IOObjectRelease(mediaIterator);
|
||||
}
|
||||
if (masterPort) {
|
||||
mach_port_deallocate(mach_task_self(),masterPort);
|
||||
}
|
||||
}
|
||||
[result setObject:from forKey:NSWorkspace_RBmntfromname];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@end
|
||||
+8
-1
@@ -11,6 +11,7 @@
|
||||
|
||||
@interface NTSynchronousTask : NSObject
|
||||
{
|
||||
@private
|
||||
NSTask *mv_task;
|
||||
NSPipe *mv_outputPipe;
|
||||
NSPipe *mv_inputPipe;
|
||||
@@ -22,7 +23,13 @@
|
||||
|
||||
// pass nil for directory if not needed
|
||||
// returns the result
|
||||
+ (NSData*)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
|
||||
+(int) task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input output: (NSData**)outData;
|
||||
|
||||
+(NSData*)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
|
||||
|
||||
- (void)run:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
|
||||
- (int)result;
|
||||
- (NSData *)output;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
+153
-147
@@ -6,151 +6,15 @@
|
||||
// Copyright 2005 Steve Gehrman. All rights reserved.
|
||||
//
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "SUUpdater.h"
|
||||
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "NTSynchronousTask.h"
|
||||
|
||||
@interface NTSynchronousTask (Private)
|
||||
- (void)run:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
|
||||
|
||||
- (NSTask *)task;
|
||||
- (void)setTask:(NSTask *)theTask;
|
||||
|
||||
- (NSPipe *)outputPipe;
|
||||
- (void)setOutputPipe:(NSPipe *)theOutputPipe;
|
||||
|
||||
- (NSPipe *)inputPipe;
|
||||
- (void)setInputPipe:(NSPipe *)theInputPipe;
|
||||
|
||||
- (NSData *)output;
|
||||
- (void)setOutput:(NSData *)theOutput;
|
||||
|
||||
- (BOOL)done;
|
||||
- (void)setDone:(BOOL)flag;
|
||||
|
||||
- (int)result;
|
||||
- (void)setResult:(int)theResult;
|
||||
@end
|
||||
|
||||
@implementation NTSynchronousTask
|
||||
|
||||
- (id)init;
|
||||
{
|
||||
self = [super init];
|
||||
if (self)
|
||||
{
|
||||
[self setTask:[[[NSTask alloc] init] autorelease]];
|
||||
[self setOutputPipe:[[[NSPipe alloc] init] autorelease]];
|
||||
[self setInputPipe:[[[NSPipe alloc] init] autorelease]];
|
||||
|
||||
[[self task] setStandardInput:[self inputPipe]];
|
||||
[[self task] setStandardOutput:[self outputPipe]];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
// dealloc
|
||||
//----------------------------------------------------------
|
||||
- (void)dealloc
|
||||
{
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
||||
|
||||
[self setTask:nil];
|
||||
[self setOutputPipe:nil];
|
||||
[self setInputPipe:nil];
|
||||
[self setOutput:nil];
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
+ (NSData*)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
|
||||
{
|
||||
// we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased
|
||||
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
|
||||
NSData* result=nil;
|
||||
|
||||
NS_DURING
|
||||
{
|
||||
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
|
||||
|
||||
[task run:toolPath directory:currentDirectory withArgs:args input:input];
|
||||
|
||||
if ([task result] == 0)
|
||||
result = [[task output] retain];
|
||||
|
||||
[task release];
|
||||
}
|
||||
NS_HANDLER;
|
||||
NS_ENDHANDLER;
|
||||
|
||||
[pool drain];
|
||||
|
||||
// retained above
|
||||
[result autorelease];
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation NTSynchronousTask (Private)
|
||||
|
||||
- (void)run:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input;
|
||||
{
|
||||
BOOL success = NO;
|
||||
|
||||
if (currentDirectory)
|
||||
[[self task] setCurrentDirectoryPath: currentDirectory];
|
||||
|
||||
[[self task] setLaunchPath:toolPath];
|
||||
[[self task] setArguments:args];
|
||||
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self
|
||||
selector:@selector(taskOutputAvailable:)
|
||||
name:NSFileHandleReadToEndOfFileCompletionNotification
|
||||
object:[[self outputPipe] fileHandleForReading]];
|
||||
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self
|
||||
selector:@selector(taskDidTerminate:)
|
||||
name:NSTaskDidTerminateNotification
|
||||
object:[self task]];
|
||||
|
||||
[[[self outputPipe] fileHandleForReading] readToEndOfFileInBackgroundAndNotifyForModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode, nil]];
|
||||
|
||||
NS_DURING
|
||||
[[self task] launch];
|
||||
success = YES;
|
||||
NS_HANDLER
|
||||
;
|
||||
NS_ENDHANDLER
|
||||
|
||||
if (success)
|
||||
{
|
||||
if (input)
|
||||
{
|
||||
// feed the running task our input
|
||||
[[[self inputPipe] fileHandleForWriting] writeData:input];
|
||||
[[[self inputPipe] fileHandleForWriting] closeFile];
|
||||
}
|
||||
|
||||
// loop until we are done receiving the data
|
||||
if (![self done])
|
||||
{
|
||||
double resolution = 1;
|
||||
BOOL isRunning;
|
||||
NSDate* next;
|
||||
|
||||
do {
|
||||
next = [NSDate dateWithTimeIntervalSinceNow:resolution];
|
||||
|
||||
isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
|
||||
beforeDate:next];
|
||||
} while (isRunning && ![self done]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
// task
|
||||
//----------------------------------------------------------
|
||||
@@ -241,10 +105,6 @@
|
||||
mv_result = theResult;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation NTSynchronousTask (Notifications)
|
||||
|
||||
- (void)taskOutputAvailable:(NSNotification*)note
|
||||
{
|
||||
[self setOutput:[[note userInfo] objectForKey:NSFileHandleNotificationDataItem]];
|
||||
@@ -257,6 +117,152 @@
|
||||
[self setResult:[[self task] terminationStatus]];
|
||||
}
|
||||
|
||||
- (id)init;
|
||||
{
|
||||
self = [super init];
|
||||
if (self)
|
||||
{
|
||||
[self setTask:[[[NSTask alloc] init] autorelease]];
|
||||
[self setOutputPipe:[[[NSPipe alloc] init] autorelease]];
|
||||
[self setInputPipe:[[[NSPipe alloc] init] autorelease]];
|
||||
|
||||
[[self task] setStandardInput:[self inputPipe]];
|
||||
[[self task] setStandardOutput:[self outputPipe]];
|
||||
[[self task] setStandardError:[self outputPipe]];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
// dealloc
|
||||
//----------------------------------------------------------
|
||||
- (void)dealloc
|
||||
{
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
||||
|
||||
[mv_task release];
|
||||
[mv_outputPipe release];
|
||||
[mv_inputPipe release];
|
||||
[mv_output release];
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (void)run:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input
|
||||
{
|
||||
BOOL success = NO;
|
||||
|
||||
if (currentDirectory)
|
||||
[[self task] setCurrentDirectoryPath: currentDirectory];
|
||||
|
||||
[[self task] setLaunchPath:toolPath];
|
||||
[[self task] setArguments:args];
|
||||
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self
|
||||
selector:@selector(taskOutputAvailable:)
|
||||
name:NSFileHandleReadToEndOfFileCompletionNotification
|
||||
object:[[self outputPipe] fileHandleForReading]];
|
||||
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self
|
||||
selector:@selector(taskDidTerminate:)
|
||||
name:NSTaskDidTerminateNotification
|
||||
object:[self task]];
|
||||
|
||||
[[[self outputPipe] fileHandleForReading] readToEndOfFileInBackgroundAndNotifyForModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode, nil]];
|
||||
|
||||
@try
|
||||
{
|
||||
[[self task] launch];
|
||||
success = YES;
|
||||
}
|
||||
@catch (NSException *localException) { }
|
||||
|
||||
if (success)
|
||||
{
|
||||
if (input)
|
||||
{
|
||||
// feed the running task our input
|
||||
[[[self inputPipe] fileHandleForWriting] writeData:input];
|
||||
[[[self inputPipe] fileHandleForWriting] closeFile];
|
||||
}
|
||||
|
||||
// loop until we are done receiving the data
|
||||
if (![self done])
|
||||
{
|
||||
double resolution = 1;
|
||||
BOOL isRunning;
|
||||
NSDate* next;
|
||||
|
||||
do {
|
||||
next = [NSDate dateWithTimeIntervalSinceNow:resolution];
|
||||
|
||||
isRunning = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
|
||||
beforeDate:next];
|
||||
} while (isRunning && ![self done]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+ (NSData*)task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input
|
||||
{
|
||||
// we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased
|
||||
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
|
||||
NSData* result=nil;
|
||||
|
||||
@try
|
||||
{
|
||||
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
|
||||
|
||||
[task run:toolPath directory:currentDirectory withArgs:args input:input];
|
||||
|
||||
if ([task result] == 0)
|
||||
result = [[task output] retain];
|
||||
|
||||
[task release];
|
||||
}
|
||||
@catch (NSException *localException) { }
|
||||
|
||||
[pool drain];
|
||||
|
||||
// retained above
|
||||
[result autorelease];
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
+(int) task:(NSString*)toolPath directory:(NSString*)currentDirectory withArgs:(NSArray*)args input:(NSData*)input output: (NSData**)outData
|
||||
{
|
||||
// we need this wacky pool here, otherwise we run out of pipes, the pipes are internally autoreleased
|
||||
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
|
||||
int taskResult = 0;
|
||||
if( outData )
|
||||
*outData = nil;
|
||||
|
||||
NS_DURING
|
||||
{
|
||||
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
|
||||
|
||||
[task run:toolPath directory:currentDirectory withArgs:args input:input];
|
||||
|
||||
taskResult = [task result];
|
||||
if( outData )
|
||||
*outData = [[task output] retain];
|
||||
|
||||
[task release];
|
||||
}
|
||||
NS_HANDLER;
|
||||
taskResult = errCppGeneral;
|
||||
NS_ENDHANDLER;
|
||||
|
||||
[pool drain];
|
||||
|
||||
// retained above
|
||||
if( outData )
|
||||
[*outData autorelease];
|
||||
|
||||
return taskResult;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,40 @@
|
||||
# Sparkle
|
||||
is an easy-to-use software update framework for Cocoa developers.
|
||||
|
||||
* True self-updating--no work required from the user.
|
||||
|
||||
* Displays release notes to the user via WebKit.
|
||||
|
||||
* Displays a detailed progress window to the user.
|
||||
|
||||
* Supports authentication for installing in secure locations.
|
||||
|
||||
* Really, really easy to install.
|
||||
|
||||
* Uses appcasts for release information.
|
||||
|
||||
* The user can choose to automatically download and install all updates.
|
||||
|
||||
* Seamless integration—there's no mention of Sparkle; your icons and app name are used.
|
||||
|
||||
* Supports DSA signatures for ultra-secure updates.
|
||||
|
||||
* Sparkle requires no code in your app, so it's trivial to upgrade or remove the module.
|
||||
|
||||
## New in Sparkle 1.5:
|
||||
|
||||
* Optionally sends user demographic information to the server when checking for updates.
|
||||
|
||||
* Dual-mode garbage collection support for any memory management style.
|
||||
|
||||
* Sparkle doesn't bug the user until second launch for better first impressions.
|
||||
|
||||
* Sparkle can install .pkg files for more complicated products.
|
||||
|
||||
* Supports bundles, preference panes, plugins, and other non-.app software.
|
||||
|
||||
* Supports branches due to minimum OS version requirements.
|
||||
|
||||
* Deep delegate support to make Sparkle work exactly as you need.
|
||||
|
||||
* Tons of other stuff! [Read more about what's new.](http://andymatuschak.org/articles/2008/05/31/sparkle-15b1-now-available/ "Sparkle 1.5b1: now available!")
|
||||
@@ -1,77 +0,0 @@
|
||||
/*
|
||||
|
||||
BSD License
|
||||
|
||||
Copyright (c) 2002, Brent Simmons
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of ranchero.com or Brent Simmons nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
|
||||
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
|
||||
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
|
||||
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
*/
|
||||
|
||||
#ifndef RSS_H
|
||||
#define RSS_H
|
||||
|
||||
|
||||
/*
|
||||
RSS.h
|
||||
A class for reading RSS feeds.
|
||||
|
||||
Created by Brent Simmons on Wed Apr 17 2002.
|
||||
Copyright (c) 2002 Brent Simmons. All rights reserved.
|
||||
*/
|
||||
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <CoreFoundation/CoreFoundation.h>
|
||||
#import "NSString+extras.h"
|
||||
|
||||
|
||||
@interface RSS : NSObject {
|
||||
NSMutableData *incrementalData;
|
||||
id delegate;
|
||||
|
||||
NSDictionary *headerItems;
|
||||
NSMutableArray *newsItems;
|
||||
NSString *version;
|
||||
|
||||
BOOL flRdf;
|
||||
BOOL normalize;
|
||||
}
|
||||
|
||||
- (RSS *)initWithURL:(NSURL *) url userAgent:(NSString*)userAgent delegate:delegate;
|
||||
- (BOOL)loadData:(NSData *)rssData normalize:(BOOL)fl;
|
||||
|
||||
- (NSMutableArray *)newsItems;
|
||||
- (NSDictionary *)newestItem;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSObject (RSSDelegateProtocol)
|
||||
- (void)feedDidFinishLoading:(RSS *)feed;
|
||||
- (void)feed:(RSS *)feed didFailWithError:(NSError *)error;
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,727 +0,0 @@
|
||||
/*
|
||||
|
||||
BSD License
|
||||
|
||||
Copyright (c) 2002, Brent Simmons
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of ranchero.com or Brent Simmons nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
|
||||
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
|
||||
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
|
||||
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
*/
|
||||
|
||||
/*
|
||||
RSS.m
|
||||
A class for reading RSS feeds.
|
||||
|
||||
Created by Brent Simmons on Wed Apr 17 2002.
|
||||
Copyright (c) 2002 Brent Simmons. All rights reserved.
|
||||
*/
|
||||
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "RSS.h"
|
||||
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
|
||||
@interface NSError (TigerPlusMethods)
|
||||
- (NSString *)localizedFailureReason;
|
||||
@end
|
||||
#endif
|
||||
|
||||
@interface RSS (Private)
|
||||
- (void) createheaderdictionary: (CFXMLTreeRef) tree;
|
||||
- (void) createitemsarray: (CFXMLTreeRef) tree;
|
||||
- (void) setversionstring: (CFXMLTreeRef) tree;
|
||||
- (void) flattenimagechildren: (CFXMLTreeRef) tree into: (NSMutableDictionary *) dictionary;
|
||||
- (void) flattensourceattributes: (CFXMLNodeRef) node into: (NSMutableDictionary *) dictionary;
|
||||
- (CFXMLTreeRef) getchanneltree: (CFXMLTreeRef) tree;
|
||||
- (CFXMLTreeRef) getnamedtree: (CFXMLTreeRef) currentTree name: (NSString *) name;
|
||||
- (void) normalizeRSSItem: (NSMutableDictionary *) rssItem;
|
||||
- (NSString *) getelementvalue: (CFXMLTreeRef) tree;
|
||||
@end
|
||||
|
||||
// This comparator function is used to sort the RSS items by their published date.
|
||||
NSComparisonResult compareNewsItems(id item1, id item2, void *context)
|
||||
{
|
||||
// We compare item2 with item1 instead of the other way 'round because we want descending, not ascending. Bit of a hack.
|
||||
return [(NSDate *)[NSDate dateWithNaturalLanguageString:[item2 objectForKey:@"pubDate"]] compare:(NSDate *)[NSDate dateWithNaturalLanguageString:[item1 objectForKey:@"pubDate"]]];
|
||||
}
|
||||
|
||||
@implementation RSS
|
||||
|
||||
|
||||
#define titleKey @"title"
|
||||
#define linkKey @"link"
|
||||
#define descriptionKey @"description"
|
||||
|
||||
|
||||
/*Public interface*/
|
||||
|
||||
- (NSDictionary *)newestItem
|
||||
{
|
||||
// The news items are already sorted by published date, descending.
|
||||
return [[self newsItems] objectAtIndex:0];
|
||||
}
|
||||
|
||||
- (RSS *) initWithTitle: (NSString *) title andDescription: (NSString *) description {
|
||||
|
||||
/*
|
||||
Create an empty feed. Useful for synthetic feeds.
|
||||
*/
|
||||
|
||||
NSMutableDictionary *header;
|
||||
|
||||
flRdf = NO;
|
||||
|
||||
header = [NSMutableDictionary dictionaryWithCapacity: 2];
|
||||
|
||||
[header setObject: title forKey: titleKey];
|
||||
|
||||
[header setObject: description forKey: descriptionKey];
|
||||
|
||||
headerItems = (NSDictionary *) [header copy];
|
||||
|
||||
newsItems = [[NSMutableArray alloc] initWithCapacity: 0];
|
||||
|
||||
version = [[NSString alloc] initWithString: @"synthetic"];
|
||||
|
||||
return (self);
|
||||
} /*initWithTitle*/
|
||||
|
||||
|
||||
- (BOOL)loadData:(NSData *)rssData normalize:(BOOL)fl
|
||||
{
|
||||
CFXMLTreeRef tree;
|
||||
flRdf = NO;
|
||||
normalize = fl;
|
||||
|
||||
NS_DURING
|
||||
tree = CFXMLTreeCreateFromData (kCFAllocatorDefault, (CFDataRef) rssData,
|
||||
NULL, kCFXMLParserSkipWhitespace, kCFXMLNodeCurrentVersion);
|
||||
NS_HANDLER
|
||||
tree = nil;
|
||||
NS_ENDHANDLER
|
||||
|
||||
if (tree == nil)
|
||||
return NO;
|
||||
|
||||
[self createheaderdictionary: tree];
|
||||
[self createitemsarray: tree];
|
||||
[self setversionstring: tree];
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
- (RSS *)initWithURL:(NSURL *)url userAgent:(NSString*)userAgent delegate:del
|
||||
{
|
||||
self = [super init];
|
||||
if (self)
|
||||
{
|
||||
delegate = del;
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringCacheData
|
||||
timeoutInterval: 30.0];
|
||||
if (userAgent)
|
||||
[request setValue: userAgent forHTTPHeaderField: @"User-Agent"];
|
||||
|
||||
incrementalData = [[NSMutableData data] retain];
|
||||
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
|
||||
CFRetain(connection);
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
|
||||
{
|
||||
[incrementalData appendData:data];
|
||||
}
|
||||
|
||||
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
|
||||
{
|
||||
CFRelease(connection);
|
||||
|
||||
NSError *error = nil;
|
||||
@try
|
||||
{
|
||||
if (![self loadData:incrementalData normalize:YES])
|
||||
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:[NSDictionary dictionaryWithObject:SULocalizedString(@"An error occurred while parsing the update feed.", nil) forKey:NSLocalizedDescriptionKey]];
|
||||
}
|
||||
@catch (NSException *parseException)
|
||||
{
|
||||
error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:SULocalizedString(@"An error occurred while parsing the update feed: %@", nil), [parseException reason]] forKey:NSLocalizedFailureReasonErrorKey]];
|
||||
}
|
||||
|
||||
if (error)
|
||||
[delegate feed:self didFailWithError:error];
|
||||
else
|
||||
[delegate feedDidFinishLoading:self];
|
||||
}
|
||||
|
||||
- (void)connection:(NSURLConnection*) connection didFailWithError:(NSError *)error
|
||||
{
|
||||
CFRelease(connection);
|
||||
[delegate feed:self didFailWithError:error];
|
||||
}
|
||||
|
||||
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
|
||||
{
|
||||
return request;
|
||||
}
|
||||
|
||||
- (NSDictionary *) headerItems {
|
||||
|
||||
return (headerItems);
|
||||
} /*headerItems*/
|
||||
|
||||
|
||||
- (NSMutableArray *) newsItems {
|
||||
|
||||
return (newsItems);
|
||||
} /*newsItems*/
|
||||
|
||||
|
||||
- (NSString *) version {
|
||||
|
||||
return (version);
|
||||
} /*version*/
|
||||
|
||||
|
||||
- (void) dealloc {
|
||||
[incrementalData release];
|
||||
[headerItems release];
|
||||
|
||||
[newsItems release];
|
||||
|
||||
[version release];
|
||||
[super dealloc];
|
||||
} /*dealloc*/
|
||||
|
||||
|
||||
|
||||
/*Private methods. Don't call these: they may change.*/
|
||||
|
||||
|
||||
- (void) createheaderdictionary: (CFXMLTreeRef) tree {
|
||||
|
||||
CFXMLTreeRef channelTree, childTree;
|
||||
CFXMLNodeRef childNode;
|
||||
CFIndex childCount, i;
|
||||
NSString *childName;
|
||||
NSMutableDictionary *headerItemsMutable;
|
||||
|
||||
channelTree = [self getchanneltree: tree];
|
||||
|
||||
if (channelTree == nil) {
|
||||
|
||||
NSException *exception = [NSException exceptionWithName: @"RSSCreateHeaderDictionaryFailed"
|
||||
reason: @"Couldn't find the channel tree." userInfo: nil];
|
||||
|
||||
[exception raise];
|
||||
} /*if*/
|
||||
|
||||
childCount = CFTreeGetChildCount (channelTree);
|
||||
|
||||
headerItemsMutable = [NSMutableDictionary dictionaryWithCapacity: childCount];
|
||||
|
||||
for (i = 0; i < childCount; i++) {
|
||||
|
||||
childTree = CFTreeGetChildAtIndex (channelTree, i);
|
||||
|
||||
childNode = CFXMLTreeGetNode (childTree);
|
||||
|
||||
childName = (NSString *) CFXMLNodeGetString (childNode);
|
||||
|
||||
if ([childName hasPrefix: @"rss:"])
|
||||
childName = [childName substringFromIndex: 4];
|
||||
|
||||
if ([childName isEqualToString: @"item"])
|
||||
break;
|
||||
|
||||
if ([childName isEqualTo: @"image"])
|
||||
[self flattenimagechildren: childTree into: headerItemsMutable];
|
||||
|
||||
[headerItemsMutable setObject: [self getelementvalue: childTree] forKey: childName];
|
||||
} /*for*/
|
||||
|
||||
headerItems = [headerItemsMutable copy];
|
||||
} /*initheaderdictionary*/
|
||||
|
||||
|
||||
- (void) createitemsarray: (CFXMLTreeRef) tree {
|
||||
|
||||
CFXMLTreeRef channelTree, childTree, itemTree;
|
||||
CFXMLNodeRef childNode, itemNode;
|
||||
NSString *childName;
|
||||
NSString *itemName, *itemValue;
|
||||
CFIndex childCount, itemChildCount, i, j;
|
||||
NSMutableDictionary *itemDictionaryMutable;
|
||||
NSMutableArray *itemsArrayMutable;
|
||||
|
||||
if (flRdf)
|
||||
channelTree = [self getnamedtree: tree name: @"rdf:RDF"];
|
||||
else
|
||||
channelTree = [self getchanneltree: tree];
|
||||
|
||||
if (channelTree == nil) {
|
||||
|
||||
NSException *exception = [NSException exceptionWithName: @"RSSCreateItemsArrayFailed"
|
||||
reason: @"Couldn't find the news items." userInfo: nil];
|
||||
|
||||
[exception raise];
|
||||
} /*if*/
|
||||
|
||||
childCount = CFTreeGetChildCount (channelTree);
|
||||
|
||||
itemsArrayMutable = [NSMutableArray arrayWithCapacity: childCount];
|
||||
|
||||
for (i = 0; i < childCount; i++) {
|
||||
|
||||
childTree = CFTreeGetChildAtIndex (channelTree, i);
|
||||
|
||||
childNode = CFXMLTreeGetNode (childTree);
|
||||
|
||||
childName = (NSString *) CFXMLNodeGetString (childNode);
|
||||
|
||||
if ([childName hasPrefix: @"rss:"])
|
||||
childName = [childName substringFromIndex: 4];
|
||||
|
||||
if (![childName isEqualToString: @"item"])
|
||||
continue;
|
||||
|
||||
itemChildCount = CFTreeGetChildCount (childTree);
|
||||
|
||||
itemDictionaryMutable = [NSMutableDictionary dictionaryWithCapacity: itemChildCount];
|
||||
|
||||
for (j = 0; j < itemChildCount; j++) {
|
||||
|
||||
itemTree = CFTreeGetChildAtIndex (childTree, j);
|
||||
|
||||
itemNode = CFXMLTreeGetNode (itemTree);
|
||||
|
||||
itemName = (NSString *) CFXMLNodeGetString (itemNode);
|
||||
|
||||
if ([itemName hasPrefix: @"rss:"])
|
||||
itemName = [itemName substringFromIndex: 4];
|
||||
|
||||
if ([itemName isEqualTo:@"enclosure"])
|
||||
{
|
||||
// Hack to add attributes to the dictionary in addition to children. (AMM)
|
||||
const CFXMLElementInfo *websiteInfo = CFXMLNodeGetInfoPtr(itemNode);
|
||||
NSMutableDictionary *enclosureDictionary = [NSMutableDictionary dictionary];
|
||||
id keyEnumerator = [(NSDictionary *)websiteInfo->attributes keyEnumerator], current;
|
||||
while ((current = [keyEnumerator nextObject]))
|
||||
{
|
||||
NSString *escapedAttributeValue = [(NSDictionary *)websiteInfo->attributes objectForKey:current];
|
||||
CFStringRef attributeValue = CFXMLCreateStringByUnescapingEntities(kCFAllocatorDefault, (CFStringRef)escapedAttributeValue, NULL);
|
||||
if (attributeValue)
|
||||
{
|
||||
// Do a stringWithString dance rather than just casting so that it's GC safe without using the 10.4+ CFMakeCollectable.
|
||||
[enclosureDictionary setObject:[NSString stringWithString:(NSString *)attributeValue] forKey:current];
|
||||
CFRelease(attributeValue);
|
||||
}
|
||||
}
|
||||
[itemDictionaryMutable setObject: enclosureDictionary forKey: itemName];
|
||||
continue;
|
||||
}
|
||||
|
||||
itemValue = [self getelementvalue: itemTree];
|
||||
|
||||
if ([itemName isEqualTo: @"source"])
|
||||
[self flattensourceattributes: itemNode into: itemDictionaryMutable];
|
||||
|
||||
[itemDictionaryMutable setObject: itemValue forKey: itemName];
|
||||
} /*for*/
|
||||
|
||||
if (normalize)
|
||||
[self normalizeRSSItem: itemDictionaryMutable];
|
||||
|
||||
[itemsArrayMutable addObject: itemDictionaryMutable];
|
||||
} /*for*/
|
||||
|
||||
// Sort the news items by published date, descending.
|
||||
newsItems = [[itemsArrayMutable sortedArrayUsingFunction:compareNewsItems context:NULL] retain];
|
||||
} /*createitemsarray*/
|
||||
|
||||
|
||||
- (void) setversionstring: (CFXMLTreeRef) tree {
|
||||
|
||||
CFXMLTreeRef rssTree;
|
||||
const CFXMLElementInfo *elementInfo;
|
||||
CFXMLNodeRef node;
|
||||
|
||||
if (flRdf) {
|
||||
|
||||
version = [[NSString alloc] initWithString: @"rdf"];
|
||||
|
||||
return;
|
||||
} /*if*/
|
||||
|
||||
rssTree = [self getnamedtree: tree name: @"rss"];
|
||||
|
||||
node = CFXMLTreeGetNode (rssTree);
|
||||
|
||||
elementInfo = CFXMLNodeGetInfoPtr (node);
|
||||
|
||||
version = [[NSString alloc] initWithString: [(NSDictionary *) (*elementInfo).attributes objectForKey: @"version"]];
|
||||
} /*setversionstring*/
|
||||
|
||||
|
||||
- (void) flattenimagechildren: (CFXMLTreeRef) tree into: (NSMutableDictionary *) dictionary {
|
||||
|
||||
CFIndex childCount = CFTreeGetChildCount (tree);
|
||||
CFIndex i = 0;
|
||||
CFXMLTreeRef childTree;
|
||||
CFXMLNodeRef childNode;
|
||||
NSString *childName, *childValue, *keyName;
|
||||
|
||||
if (childCount < 1)
|
||||
return;
|
||||
|
||||
for (i = 0; i < childCount; i++) {
|
||||
|
||||
childTree = CFTreeGetChildAtIndex (tree, i);
|
||||
|
||||
childNode = CFXMLTreeGetNode (childTree);
|
||||
|
||||
childName = (NSString *) CFXMLNodeGetString (childNode);
|
||||
|
||||
if ([childName hasPrefix: @"rss:"])
|
||||
childName = [childName substringFromIndex: 4];
|
||||
|
||||
childValue = [self getelementvalue: childTree];
|
||||
|
||||
keyName = [NSString stringWithFormat: @"image%@", childName];
|
||||
|
||||
[dictionary setObject: childValue forKey: keyName];
|
||||
} /*for*/
|
||||
} /*flattenimagechildren*/
|
||||
|
||||
|
||||
- (void) flattensourceattributes: (CFXMLNodeRef) node into: (NSMutableDictionary *) dictionary {
|
||||
|
||||
const CFXMLElementInfo *elementInfo;
|
||||
NSString *sourceHomeUrl, *sourceRssUrl;
|
||||
|
||||
elementInfo = CFXMLNodeGetInfoPtr (node);
|
||||
|
||||
sourceHomeUrl = [(NSDictionary *) (*elementInfo).attributes objectForKey: @"homeUrl"];
|
||||
|
||||
sourceRssUrl = [(NSDictionary *) (*elementInfo).attributes objectForKey: @"url"];
|
||||
|
||||
if (sourceHomeUrl != nil)
|
||||
[dictionary setObject: sourceHomeUrl forKey: @"sourceHomeUrl"];
|
||||
|
||||
if (sourceRssUrl != nil)
|
||||
[dictionary setObject: sourceRssUrl forKey: @"sourceRssUrl"];
|
||||
} /*flattensourceattributes*/
|
||||
|
||||
|
||||
- (CFXMLTreeRef) getchanneltree: (CFXMLTreeRef) tree {
|
||||
|
||||
CFXMLTreeRef rssTree, channelTree;
|
||||
|
||||
rssTree = [self getnamedtree: tree name: @"rss"];
|
||||
|
||||
if (rssTree == nil) { /*It might be "rdf:RDF" instead, a 1.0 or greater feed.*/
|
||||
|
||||
rssTree = [self getnamedtree: tree name: @"rdf:RDF"];
|
||||
|
||||
if (rssTree != nil)
|
||||
flRdf = YES; /*This info will be needed later when creating the items array.*/
|
||||
} /*if*/
|
||||
|
||||
if (rssTree == nil)
|
||||
return (nil);
|
||||
|
||||
channelTree = [self getnamedtree: rssTree name: @"channel"];
|
||||
|
||||
if (channelTree == nil)
|
||||
channelTree = [self getnamedtree: rssTree name: @"rss:channel"];
|
||||
|
||||
return (channelTree);
|
||||
} /*getchanneltree*/
|
||||
|
||||
|
||||
- (CFXMLTreeRef) getnamedtree: (CFXMLTreeRef) currentTree name: (NSString *) name {
|
||||
|
||||
CFIndex childCount, i;
|
||||
CFXMLNodeRef xmlNode;
|
||||
CFXMLTreeRef xmlTreeNode;
|
||||
NSString *itemName;
|
||||
|
||||
childCount = CFTreeGetChildCount (currentTree);
|
||||
|
||||
for (i = childCount - 1; i >= 0; i--) {
|
||||
|
||||
xmlTreeNode = CFTreeGetChildAtIndex (currentTree, i);
|
||||
|
||||
xmlNode = CFXMLTreeGetNode (xmlTreeNode);
|
||||
|
||||
itemName = (NSString *) CFXMLNodeGetString (xmlNode);
|
||||
|
||||
if ([itemName isEqualToString: name])
|
||||
return (xmlTreeNode);
|
||||
} /*for*/
|
||||
|
||||
return (nil);
|
||||
} /*getnamedtree*/
|
||||
|
||||
|
||||
- (void) normalizeRSSItem: (NSMutableDictionary *) rssItem {
|
||||
|
||||
/*
|
||||
Make sure item, link, and description are present and have
|
||||
reasonable values. Description and link may be "".
|
||||
Also trim white space, remove HTML when appropriate.
|
||||
*/
|
||||
|
||||
NSString *description, *normalizedLink, *title;
|
||||
BOOL nilDescription = NO;
|
||||
|
||||
/*Description*/
|
||||
|
||||
description = [rssItem objectForKey: descriptionKey];
|
||||
|
||||
if (description == nil) {
|
||||
|
||||
description = @"";
|
||||
|
||||
nilDescription = YES;
|
||||
} /*if*/
|
||||
|
||||
description = [description trimWhiteSpace];
|
||||
|
||||
if ([description isEqualTo: @""])
|
||||
nilDescription = YES;
|
||||
|
||||
[rssItem setObject: description forKey: descriptionKey];
|
||||
|
||||
/*Link*/
|
||||
|
||||
normalizedLink = [rssItem objectForKey: linkKey];
|
||||
|
||||
if ([NSString stringIsEmpty: normalizedLink]) {
|
||||
|
||||
/*Try to get a URL from the description.*/
|
||||
|
||||
if (!nilDescription) {
|
||||
|
||||
NSArray *stringComponents = [description componentsSeparatedByString: @"href=\""];
|
||||
|
||||
if ([stringComponents count] > 1) {
|
||||
|
||||
normalizedLink = [stringComponents objectAtIndex: 1];
|
||||
|
||||
stringComponents = [normalizedLink componentsSeparatedByString: @"\""];
|
||||
|
||||
normalizedLink = [stringComponents objectAtIndex: 0];
|
||||
} /*if*/
|
||||
} /*if*/
|
||||
} /*if*/
|
||||
|
||||
if (normalizedLink == nil)
|
||||
normalizedLink = @"";
|
||||
|
||||
normalizedLink = [normalizedLink trimWhiteSpace];
|
||||
|
||||
[rssItem setObject: normalizedLink forKey: linkKey];
|
||||
|
||||
/*Title*/
|
||||
|
||||
title = [rssItem objectForKey: titleKey];
|
||||
|
||||
if (title != nil) {
|
||||
|
||||
title = [title stripHTML];
|
||||
|
||||
title = [title trimWhiteSpace];
|
||||
} /*if*/
|
||||
|
||||
if ([NSString stringIsEmpty: title]) {
|
||||
|
||||
/*Grab a title from the description.*/
|
||||
|
||||
if (!nilDescription) {
|
||||
|
||||
NSArray *stringComponents = [description componentsSeparatedByString: @">"];
|
||||
|
||||
if ([stringComponents count] > 1) {
|
||||
|
||||
title = [stringComponents objectAtIndex: 1];
|
||||
|
||||
stringComponents = [title componentsSeparatedByString: @"<"];
|
||||
|
||||
title = [stringComponents objectAtIndex: 0];
|
||||
|
||||
title = [title stripHTML];
|
||||
|
||||
title = [title trimWhiteSpace];
|
||||
} /*if*/
|
||||
|
||||
if ([NSString stringIsEmpty: title]) { /*use first part of description*/
|
||||
|
||||
NSString *shortTitle = [[[description stripHTML] trimWhiteSpace] ellipsizeAfterNWords: 5];
|
||||
|
||||
shortTitle = [shortTitle trimWhiteSpace];
|
||||
|
||||
title = [NSString stringWithFormat: @"%@\u2026", shortTitle];
|
||||
} /*else*/
|
||||
} /*if*/
|
||||
|
||||
title = [title stripHTML];
|
||||
|
||||
title = [title trimWhiteSpace];
|
||||
|
||||
if ([NSString stringIsEmpty: title])
|
||||
title = @"Untitled";
|
||||
} /*if*/
|
||||
|
||||
[rssItem setObject: title forKey: titleKey];
|
||||
|
||||
/*dangerousmeta case: super-long title with no description*/
|
||||
|
||||
if ((nilDescription) && ([title length] > 50)) {
|
||||
|
||||
NSString *shortTitle = [[[title stripHTML] trimWhiteSpace] ellipsizeAfterNWords: 7];
|
||||
|
||||
description = [[title copy] autorelease];
|
||||
|
||||
[rssItem setObject: description forKey: descriptionKey];
|
||||
|
||||
title = [NSString stringWithFormat: @"%@\u2026", shortTitle];
|
||||
|
||||
[rssItem setObject: title forKey: titleKey];
|
||||
} /*if*/
|
||||
|
||||
{ /*deal with entities*/
|
||||
|
||||
const char *tempcstring;
|
||||
NSAttributedString *s = nil;
|
||||
NSString *convertedTitle = nil;
|
||||
NSArray *stringComponents;
|
||||
|
||||
stringComponents = [title componentsSeparatedByString: @"&"];
|
||||
|
||||
if ([stringComponents count] > 1) {
|
||||
|
||||
stringComponents = [title componentsSeparatedByString: @";"];
|
||||
|
||||
if ([stringComponents count] > 1) {
|
||||
|
||||
size_t len;
|
||||
|
||||
tempcstring = [title UTF8String];
|
||||
|
||||
len = strlen (tempcstring);
|
||||
|
||||
if (len > 0) {
|
||||
|
||||
s = [[NSAttributedString alloc]
|
||||
initWithHTML: [NSData dataWithBytes: tempcstring length: strlen (tempcstring)]
|
||||
documentAttributes: (NSDictionary **) NULL];
|
||||
|
||||
convertedTitle = [s string];
|
||||
|
||||
[s autorelease];
|
||||
|
||||
convertedTitle = [convertedTitle stripHTML];
|
||||
|
||||
convertedTitle = [convertedTitle trimWhiteSpace];
|
||||
} /*if*/
|
||||
|
||||
if ([NSString stringIsEmpty: convertedTitle])
|
||||
convertedTitle = @"Untitled";
|
||||
|
||||
[rssItem setObject: convertedTitle forKey: @"convertedTitle"];
|
||||
} /*if*/
|
||||
} /*if*/
|
||||
} /*deal with entities*/
|
||||
} /*normalizeRSSItem*/
|
||||
|
||||
|
||||
- (NSString *) getelementvalue: (CFXMLTreeRef) tree {
|
||||
|
||||
CFXMLNodeRef node;
|
||||
CFXMLTreeRef itemTree;
|
||||
CFIndex childCount, ix;
|
||||
NSMutableString *valueMutable;
|
||||
NSString *value;
|
||||
NSString *name;
|
||||
|
||||
childCount = CFTreeGetChildCount (tree);
|
||||
|
||||
valueMutable = [[NSMutableString alloc] init];
|
||||
|
||||
for (ix = 0; ix < childCount; ix++) {
|
||||
|
||||
itemTree = CFTreeGetChildAtIndex (tree, ix);
|
||||
|
||||
node = CFXMLTreeGetNode (itemTree);
|
||||
|
||||
name = (NSString *) CFXMLNodeGetString (node);
|
||||
|
||||
if (name != nil) {
|
||||
|
||||
if (CFXMLNodeGetTypeCode (node) == kCFXMLNodeTypeEntityReference) {
|
||||
|
||||
if ([name isEqualTo: @"lt"])
|
||||
name = @"<";
|
||||
|
||||
else if ([name isEqualTo: @"gt"])
|
||||
name = @">";
|
||||
|
||||
else if ([name isEqualTo: @"quot"])
|
||||
name = @"\"";
|
||||
|
||||
else if ([name isEqualTo: @"amp"])
|
||||
name = @"&";
|
||||
|
||||
else if ([name isEqualTo: @"rsquo"]) {
|
||||
char rsquo[4] = { 0xe2, 0x80, 0x99, 0x0 };
|
||||
name = [NSString stringWithUTF8String: rsquo];
|
||||
}
|
||||
|
||||
else if ([name isEqualTo: @"lsquo"]) {
|
||||
char lsquo[4] = { 0xe2, 0x80, 0x98, 0x0 };
|
||||
name = [NSString stringWithUTF8String: lsquo];
|
||||
}
|
||||
|
||||
else if ([name isEqualTo: @"apos"])
|
||||
name = @"'";
|
||||
else
|
||||
name = [NSString stringWithFormat: @"&%@;", name];
|
||||
} /*if*/
|
||||
|
||||
[valueMutable appendString: name];
|
||||
} /*if*/
|
||||
} /*for*/
|
||||
|
||||
value = [[valueMutable trimWhiteSpace] retain];
|
||||
|
||||
[valueMutable autorelease];
|
||||
|
||||
return ([value autorelease]);
|
||||
} /*getelementvalue*/
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,13 @@
|
||||
{\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf200
|
||||
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
|
||||
{\colortbl;\red255\green255\blue255;\red38\green38\blue38;}
|
||||
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
|
||||
\deftab720
|
||||
\pard\pardeftab720
|
||||
|
||||
\f0\b\fs26 \cf2 Version 2.0\
|
||||
\pard\pardeftab720\sl380
|
||||
|
||||
\b0 \cf2 \'96 Works correctly with Sandboxed environment\
|
||||
\'96 Added simple integration of beta updates check and test mode\
|
||||
\'96 Integrated with DevMate service (sends additional info for statistics)}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?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>^Resources/</key>
|
||||
<true/>
|
||||
<key>^Resources/.*\.lproj/</key>
|
||||
<dict>
|
||||
<key>optional</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>1000</real>
|
||||
</dict>
|
||||
<key>^Resources/.*\.lproj/locversion.plist$</key>
|
||||
<dict>
|
||||
<key>omit</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>1100</real>
|
||||
</dict>
|
||||
<key>^version.plist$</key>
|
||||
<true/>
|
||||
<key>^Headers/</key>
|
||||
<dict>
|
||||
<key>omit</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>1000</real>
|
||||
</dict>
|
||||
<key>^PrivateHeaders/</key>
|
||||
<dict>
|
||||
<key>omit</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>1000</real>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
+11
-4
@@ -9,22 +9,29 @@
|
||||
#ifndef SUAPPCAST_H
|
||||
#define SUAPPCAST_H
|
||||
|
||||
@class RSS, SUAppcastItem;
|
||||
@interface SUAppcast : NSObject {
|
||||
@class SUAppcastItem;
|
||||
@interface SUAppcast : NSObject
|
||||
{
|
||||
@private
|
||||
NSArray *items;
|
||||
NSString *userAgentString;
|
||||
NSMutableDictionary *appcastValues;
|
||||
id delegate;
|
||||
NSString *downloadFilename;
|
||||
NSURLDownload *download;
|
||||
}
|
||||
|
||||
- (void)fetchAppcastFromURL:(NSURL *)url;
|
||||
- (void)setDelegate:delegate;
|
||||
- (void)setDelegate:(id)delegate;
|
||||
- (void)setUserAgentString:(NSString *)userAgentString;
|
||||
- (void)setAppcastValue:(NSString *)value forKey:(NSString *)key;
|
||||
- (void)setAllAppcastValues:(NSDictionary *)inAppcastValues;
|
||||
|
||||
- (NSArray *)items;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSObject (SUAppcastDelegate)
|
||||
- (void)appcast:(SUAppcast *)appcast willFetchURLRequest:(NSMutableURLRequest *)request;
|
||||
- (void)appcastDidFinishLoading:(SUAppcast *)appcast;
|
||||
- (void)appcast:(SUAppcast *)appcast failedToLoadWithError:(NSError *)error;
|
||||
@end
|
||||
|
||||
+277
-27
@@ -6,11 +6,36 @@
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "SUAppcast.h"
|
||||
#import "SUUpdater_Private.h"
|
||||
|
||||
@interface SUAppcast (Private)
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUAppcast.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SULog.h"
|
||||
#import "SUXPCURLDownload.h"
|
||||
|
||||
@interface NSXMLElement (SUAppcastExtensions)
|
||||
- (NSDictionary *)attributesAsDictionary;
|
||||
@end
|
||||
|
||||
@implementation NSXMLElement (SUAppcastExtensions)
|
||||
- (NSDictionary *)attributesAsDictionary
|
||||
{
|
||||
NSEnumerator *attributeEnum = [[self attributes] objectEnumerator];
|
||||
NSXMLNode *attribute;
|
||||
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
|
||||
|
||||
while ((attribute = [attributeEnum nextObject]))
|
||||
[dictionary setObject:[attribute stringValue] forKey:[attribute name]];
|
||||
return dictionary;
|
||||
}
|
||||
@end
|
||||
|
||||
@interface SUAppcast () <NSURLDownloadDelegate>
|
||||
- (void)reportError:(NSError *)error;
|
||||
- (NSXMLNode *)bestNodeInNodes:(NSArray *)nodes;
|
||||
@end
|
||||
|
||||
@implementation SUAppcast
|
||||
@@ -18,6 +43,10 @@
|
||||
- (void)dealloc
|
||||
{
|
||||
[items release];
|
||||
[appcastValues release];
|
||||
[downloadFilename release];
|
||||
[download release];
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
@@ -28,38 +57,207 @@
|
||||
|
||||
- (void)fetchAppcastFromURL:(NSURL *)url
|
||||
{
|
||||
RSS *feed = [[RSS alloc] initWithURL:url userAgent:userAgentString delegate:self];
|
||||
CFRetain(feed); // Manage the RSS feed's memory manually.
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
|
||||
if ([appcastValues count])
|
||||
[request setAllHTTPHeaderFields:appcastValues];
|
||||
|
||||
if ([delegate respondsToSelector:@selector(appcast:willFetchURLRequest:)])
|
||||
[delegate appcast:self willFetchURLRequest:request];
|
||||
|
||||
if ([SUUpdater shouldUseXPCDownloader])
|
||||
{
|
||||
download = (NSURLDownload *)[[SUXPCURLDownload alloc] initWithRequest:request delegate:self];
|
||||
}
|
||||
else
|
||||
{
|
||||
download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)feedDidFinishLoading:(RSS *)feed
|
||||
- (void)download:(NSURLDownload *)aDownload decideDestinationWithSuggestedFilename:(NSString *)filename
|
||||
{
|
||||
// Set up all the appcast items:
|
||||
NSArray *tempItems = [NSMutableArray array];
|
||||
id enumerator = [[feed newsItems] objectEnumerator], current;
|
||||
@try
|
||||
NSString* destinationFilename = NSTemporaryDirectory();
|
||||
if (destinationFilename)
|
||||
{
|
||||
while ((current = [enumerator nextObject]))
|
||||
{
|
||||
[(NSMutableArray *)tempItems addObject:[[[SUAppcastItem alloc] initWithDictionary:current] autorelease]];
|
||||
}
|
||||
items = [[NSArray arrayWithArray:tempItems] retain]; // Make the items list immutable.
|
||||
destinationFilename = [destinationFilename stringByAppendingPathComponent:filename];
|
||||
[download setDestination:destinationFilename allowOverwrite:NO];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)aDownload didCreateDestination:(NSString *)path
|
||||
{
|
||||
[downloadFilename release];
|
||||
downloadFilename = [path copy];
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish:(NSURLDownload *)aDownload
|
||||
{
|
||||
NSError *error = nil;
|
||||
|
||||
NSXMLDocument *document = nil;
|
||||
BOOL failed = NO;
|
||||
NSArray *xmlItems = nil;
|
||||
NSMutableArray *appcastItems = [NSMutableArray array];
|
||||
|
||||
if (downloadFilename)
|
||||
{
|
||||
NSUInteger options = 0;
|
||||
if (NSAppKitVersionNumber < NSAppKitVersionNumber10_7) {
|
||||
// In order to avoid including external entities when parsing the appcast (a potential security vulnerability; see https://github.com/andymatuschak/Sparkle/issues/169), we ask NSXMLDocument to "tidy" the XML first. This happens to remove these external entities; it wouldn't be a future-proof approach, but it worked in these historical versions of OS X, and we have a more rigorous approach for 10.7+.
|
||||
options = NSXMLDocumentTidyXML;
|
||||
} else {
|
||||
// In 10.7 and later, there's a real option for the behavior we desire.
|
||||
options = NSXMLNodeLoadExternalEntitiesSameOriginOnly;
|
||||
}
|
||||
document = [[[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:downloadFilename] options:options error:&error] autorelease];
|
||||
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
|
||||
[[NSFileManager defaultManager] removeFileAtPath:downloadFilename handler:nil];
|
||||
#else
|
||||
[[NSFileManager defaultManager] removeItemAtPath:downloadFilename error:nil];
|
||||
#endif
|
||||
[downloadFilename release];
|
||||
downloadFilename = nil;
|
||||
}
|
||||
else
|
||||
{
|
||||
failed = YES;
|
||||
}
|
||||
|
||||
if (nil == document)
|
||||
{
|
||||
failed = YES;
|
||||
}
|
||||
else
|
||||
{
|
||||
xmlItems = [document nodesForXPath:@"/rss/channel/item" error:&error];
|
||||
if (nil == xmlItems)
|
||||
{
|
||||
failed = YES;
|
||||
}
|
||||
}
|
||||
|
||||
if (failed == NO)
|
||||
{
|
||||
|
||||
if ([delegate respondsToSelector:@selector(appcastDidFinishLoading:)])
|
||||
[delegate performSelectorOnMainThread:@selector(appcastDidFinishLoading:) withObject:self waitUntilDone:NO];
|
||||
NSEnumerator *nodeEnum = [xmlItems objectEnumerator];
|
||||
NSXMLNode *node;
|
||||
NSMutableDictionary *nodesDict = [NSMutableDictionary dictionary];
|
||||
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
|
||||
|
||||
while (failed == NO && (node = [nodeEnum nextObject]))
|
||||
{
|
||||
// First, we'll "index" all the first-level children of this appcast item so we can pick them out by language later.
|
||||
if ([[node children] count])
|
||||
{
|
||||
node = [node childAtIndex:0];
|
||||
while (nil != node)
|
||||
{
|
||||
NSString *name = [node name];
|
||||
if (name)
|
||||
{
|
||||
NSMutableArray *nodes = [nodesDict objectForKey:name];
|
||||
if (nodes == nil)
|
||||
{
|
||||
nodes = [NSMutableArray array];
|
||||
[nodesDict setObject:nodes forKey:name];
|
||||
}
|
||||
[nodes addObject:node];
|
||||
}
|
||||
node = [node nextSibling];
|
||||
}
|
||||
}
|
||||
|
||||
NSEnumerator *nameEnum = [nodesDict keyEnumerator];
|
||||
NSString *name;
|
||||
while ((name = [nameEnum nextObject]))
|
||||
{
|
||||
node = [self bestNodeInNodes:[nodesDict objectForKey:name]];
|
||||
if ([name isEqualToString:@"enclosure"])
|
||||
{
|
||||
// enclosure is flattened as a separate dictionary for some reason
|
||||
NSDictionary *encDict = [(NSXMLElement *)node attributesAsDictionary];
|
||||
[dict setObject:encDict forKey:@"enclosure"];
|
||||
|
||||
}
|
||||
else if ([name isEqualToString:@"pubDate"])
|
||||
{
|
||||
// pubDate is expected to be an NSDate by SUAppcastItem, but the RSS class was returning an NSString
|
||||
NSDate *date = [NSDate dateWithNaturalLanguageString:[node stringValue]];
|
||||
if (date)
|
||||
[dict setObject:date forKey:name];
|
||||
}
|
||||
else if ([name isEqualToString:@"sparkle:deltas"])
|
||||
{
|
||||
NSMutableArray *deltas = [NSMutableArray array];
|
||||
NSEnumerator *childEnum = [[node children] objectEnumerator];
|
||||
NSXMLNode *child;
|
||||
while ((child = [childEnum nextObject])) {
|
||||
if ([[child name] isEqualToString:@"enclosure"])
|
||||
[deltas addObject:[(NSXMLElement *)child attributesAsDictionary]];
|
||||
}
|
||||
[dict setObject:deltas forKey:@"deltas"];
|
||||
}
|
||||
else if (name != nil)
|
||||
{
|
||||
// add all other values as strings
|
||||
[dict setObject:[[node stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:name];
|
||||
}
|
||||
}
|
||||
|
||||
NSString *errString;
|
||||
SUAppcastItem *anItem = [[[SUAppcastItem alloc] initWithDictionary:dict failureReason:&errString] autorelease];
|
||||
if (anItem)
|
||||
{
|
||||
[appcastItems addObject:anItem];
|
||||
}
|
||||
else
|
||||
{
|
||||
SULog(@"Sparkle Updater: Failed to parse appcast item: %@.\nAppcast dictionary was: %@", errString, dict);
|
||||
}
|
||||
[nodesDict removeAllObjects];
|
||||
[dict removeAllObjects];
|
||||
}
|
||||
}
|
||||
@catch (NSException *parseException)
|
||||
{
|
||||
[self reportError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while parsing the update feed.", nil), NSLocalizedDescriptionKey, [parseException reason], SUTechnicalErrorInformationKey, nil]]];
|
||||
|
||||
if ([appcastItems count])
|
||||
{
|
||||
NSSortDescriptor *sort = [[[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO] autorelease];
|
||||
[appcastItems sortUsingDescriptors:[NSArray arrayWithObject:sort]];
|
||||
items = [appcastItems copy];
|
||||
}
|
||||
|
||||
if (failed)
|
||||
{
|
||||
[self reportError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while parsing the update feed.", nil), NSLocalizedDescriptionKey, nil]]];
|
||||
}
|
||||
else if ([delegate respondsToSelector:@selector(appcastDidFinishLoading:)])
|
||||
{
|
||||
[delegate appcastDidFinishLoading:self];
|
||||
}
|
||||
CFRelease(feed);
|
||||
}
|
||||
|
||||
- (void)feed:(RSS *)feed didFailWithError:(NSError *)error
|
||||
- (void)download:(NSURLDownload *)aDownload didFailWithError:(NSError *)error
|
||||
{
|
||||
if (downloadFilename)
|
||||
{
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
|
||||
[[NSFileManager defaultManager] removeFileAtPath:downloadFilename handler:nil];
|
||||
#else
|
||||
[[NSFileManager defaultManager] removeItemAtPath:downloadFilename error:nil];
|
||||
#endif
|
||||
}
|
||||
[downloadFilename release];
|
||||
downloadFilename = nil;
|
||||
|
||||
[self reportError:error];
|
||||
}
|
||||
|
||||
- (NSURLRequest *)download:(NSURLDownload *)aDownload willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
|
||||
{
|
||||
return request;
|
||||
}
|
||||
|
||||
- (void)reportError:(NSError *)error
|
||||
{
|
||||
if ([delegate respondsToSelector:@selector(appcast:failedToLoadWithError:)])
|
||||
@@ -68,13 +266,65 @@
|
||||
}
|
||||
}
|
||||
|
||||
- (NSXMLNode *)bestNodeInNodes:(NSArray *)nodes
|
||||
{
|
||||
// We use this method to pick out the localized version of a node when one's available.
|
||||
if ([nodes count] == 1)
|
||||
return [nodes objectAtIndex:0];
|
||||
else if ([nodes count] == 0)
|
||||
return nil;
|
||||
|
||||
NSEnumerator *nodeEnum = [nodes objectEnumerator];
|
||||
NSXMLElement *node;
|
||||
NSMutableArray *languages = [NSMutableArray array];
|
||||
NSString *lang;
|
||||
NSUInteger i;
|
||||
while ((node = [nodeEnum nextObject]))
|
||||
{
|
||||
lang = [[node attributeForName:@"xml:lang"] stringValue];
|
||||
[languages addObject:(lang ? lang : @"")];
|
||||
}
|
||||
lang = [[NSBundle preferredLocalizationsFromArray:languages] objectAtIndex:0];
|
||||
i = [languages indexOfObject:([languages containsObject:lang] ? lang : @"")];
|
||||
if (i == NSNotFound)
|
||||
i = 0;
|
||||
return [nodes objectAtIndex:i];
|
||||
}
|
||||
|
||||
- (void)setUserAgentString:(NSString *)uas
|
||||
{
|
||||
if (uas != userAgentString)
|
||||
{
|
||||
[userAgentString release];
|
||||
userAgentString = [uas copy];
|
||||
}
|
||||
[self setAppcastValue:uas forKey:@"User-Agent"];
|
||||
}
|
||||
|
||||
- (void)setAppcastValue:(NSString *)value forKey:(NSString *)key
|
||||
{
|
||||
if (nil == key)
|
||||
return;
|
||||
|
||||
if (nil == appcastValues)
|
||||
appcastValues = [[NSMutableDictionary alloc] init];
|
||||
|
||||
if (nil == value)
|
||||
[appcastValues removeObjectForKey:key];
|
||||
else
|
||||
[appcastValues setValue:[[value copy] autorelease] forKey:key];
|
||||
}
|
||||
|
||||
- (void)setAllAppcastValues:(NSDictionary *)inAppcastValues
|
||||
{
|
||||
if (0 == [inAppcastValues count])
|
||||
return;
|
||||
|
||||
NSEnumerator *keyEnumerator = [inAppcastValues keyEnumerator];
|
||||
id key = nil;
|
||||
while ((key = [keyEnumerator nextObject]))
|
||||
{
|
||||
id value = [inAppcastValues objectForKey:key];
|
||||
if (![key isKindOfClass:[NSString class]] || ![value isKindOfClass:[NSString class]])
|
||||
continue;
|
||||
|
||||
[self setAppcastValue:value forKey:key];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setDelegate:del
|
||||
|
||||
+17
-5
@@ -9,40 +9,52 @@
|
||||
#ifndef SUAPPCASTITEM_H
|
||||
#define SUAPPCASTITEM_H
|
||||
|
||||
|
||||
@interface SUAppcastItem : NSObject {
|
||||
@interface SUAppcastItem : NSObject
|
||||
{
|
||||
@private
|
||||
NSString *title;
|
||||
NSDate *date;
|
||||
NSString *description;
|
||||
NSString *itemDescription;
|
||||
|
||||
NSURL *releaseNotesURL;
|
||||
|
||||
NSString *DSASignature;
|
||||
NSString *minimumSystemVersion;
|
||||
NSString *maximumSystemVersion;
|
||||
|
||||
NSURL *fileURL;
|
||||
NSString *versionString;
|
||||
NSString *displayVersionString;
|
||||
|
||||
|
||||
NSDictionary *deltaUpdates;
|
||||
|
||||
NSDictionary *propertiesDictionary;
|
||||
|
||||
NSURL *infoURL; // UK 2007-08-31
|
||||
}
|
||||
|
||||
// Initializes with data from a dictionary provided by the RSS class.
|
||||
- initWithDictionary:(NSDictionary *)dict;
|
||||
- initWithDictionary:(NSDictionary *)dict failureReason:(NSString**)error;
|
||||
|
||||
- (NSString *)title;
|
||||
- (NSString *)versionString;
|
||||
- (NSString *)displayVersionString;
|
||||
- (NSDate *)date;
|
||||
- (NSString *)description;
|
||||
- (NSString *)itemDescription;
|
||||
- (NSURL *)releaseNotesURL;
|
||||
- (NSURL *)fileURL;
|
||||
- (NSString *)DSASignature;
|
||||
- (NSString *)minimumSystemVersion;
|
||||
- (NSString *)maximumSystemVersion;
|
||||
- (NSDictionary *)deltaUpdates;
|
||||
- (BOOL)isDeltaUpdate;
|
||||
|
||||
// Returns the dictionary provided in initWithDictionary; this might be useful later for extensions.
|
||||
- (NSDictionary *)propertiesDictionary;
|
||||
|
||||
- (NSURL *)infoURL; // UK 2007-08-31
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
+131
-25
@@ -6,8 +6,13 @@
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "SUUpdater.h"
|
||||
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SULog.h"
|
||||
|
||||
@implementation SUAppcastItem
|
||||
|
||||
@@ -33,13 +38,13 @@
|
||||
}
|
||||
|
||||
|
||||
- (NSString *)description { return [[description retain] autorelease]; }
|
||||
- (NSString *)itemDescription { return [[itemDescription retain] autorelease]; }
|
||||
|
||||
- (void)setDescription:(NSString *)aDescription
|
||||
- (void)setItemDescription:(NSString *)anItemDescription
|
||||
{
|
||||
if (description == aDescription) return;
|
||||
[description release];
|
||||
description = [aDescription copy];
|
||||
if (itemDescription == anItemDescription) return;
|
||||
[itemDescription release];
|
||||
itemDescription = [anItemDescription copy];
|
||||
}
|
||||
|
||||
|
||||
@@ -101,21 +106,49 @@
|
||||
minimumSystemVersion = [systemVersionString copy];
|
||||
}
|
||||
|
||||
- (NSString *)maximumSystemVersion { return [[maximumSystemVersion retain] autorelease]; }
|
||||
- (void)setMaximumSystemVersion:(NSString *)systemVersionString
|
||||
{
|
||||
if (maximumSystemVersion == systemVersionString) return;
|
||||
[maximumSystemVersion release];
|
||||
maximumSystemVersion = [systemVersionString copy];
|
||||
}
|
||||
|
||||
|
||||
- (NSURL *)infoURL { return [[infoURL retain] autorelease]; } // UK 2007-08-31 (whole method)
|
||||
|
||||
- (void)setInfoURL:(NSURL *)aFileURL // UK 2007-08-31 (whole method)
|
||||
{
|
||||
if( aFileURL == infoURL ) return;
|
||||
[infoURL release];
|
||||
infoURL = [aFileURL copy];
|
||||
}
|
||||
|
||||
- (NSDictionary *)deltaUpdates { return [[deltaUpdates retain] autorelease]; }
|
||||
|
||||
- (void)setDeltaUpdates:(NSDictionary *)updates
|
||||
{
|
||||
if (deltaUpdates == updates) return;
|
||||
[deltaUpdates release];
|
||||
deltaUpdates = [updates copy];
|
||||
}
|
||||
|
||||
- (BOOL)isDeltaUpdate
|
||||
{
|
||||
return [[propertiesDictionary objectForKey:@"enclosure"] objectForKey:@"sparkle:deltaFrom"] != nil;
|
||||
}
|
||||
|
||||
- initWithDictionary:(NSDictionary *)dict
|
||||
{
|
||||
return [self initWithDictionary:dict failureReason:nil];
|
||||
}
|
||||
|
||||
- initWithDictionary:(NSDictionary *)dict failureReason:(NSString**)error
|
||||
{
|
||||
self = [super init];
|
||||
if (self)
|
||||
{
|
||||
propertiesDictionary = [dict retain];
|
||||
[self setTitle:[dict objectForKey:@"title"]];
|
||||
[self setDate:[dict objectForKey:@"pubDate"]];
|
||||
[self setDescription:[dict objectForKey:@"description"]];
|
||||
|
||||
id enclosure = [dict objectForKey:@"enclosure"];
|
||||
if (enclosure == nil || [enclosure objectForKey:@"url"] == nil)
|
||||
[NSException raise:@"SUAppcastException" format:@"Couldn't find an download URL for feed entry %@!", [self title]];
|
||||
[self setFileURL:[NSURL URLWithString:[[enclosure objectForKey:@"url"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
|
||||
[self setDSASignature:[enclosure objectForKey:@"sparkle:dsaSignature"]];
|
||||
|
||||
// Try to find a version string.
|
||||
// Finding the new version number from the RSS feed is a little bit hacky. There are two ways:
|
||||
@@ -126,32 +159,103 @@
|
||||
// The big caveat with this is that you can't have underscores in your version strings, as that'll confuse Sparkle.
|
||||
// Feel free to change the separator string to a hyphen or something more suited to your needs if you like.
|
||||
NSString *newVersion = [enclosure objectForKey:@"sparkle:version"];
|
||||
if (!newVersion) // no sparkle:version attribute
|
||||
if( newVersion == nil )
|
||||
newVersion = [dict objectForKey:@"sparkle:version"]; // UK 2007-08-31 Get version from the item, in case it's a download-less item (i.e. paid upgrade).
|
||||
if (newVersion == nil) // no sparkle:version attribute anywhere?
|
||||
{
|
||||
// Separate the url by underscores and take the last component, as that'll be closest to the end,
|
||||
// then we remove the extension. Hopefully, this will be the version.
|
||||
NSArray *fileComponents = [[enclosure objectForKey:@"url"] componentsSeparatedByString:@"_"];
|
||||
if ([fileComponents count] > 1)
|
||||
newVersion = [[fileComponents lastObject] stringByDeletingPathExtension];
|
||||
else
|
||||
[NSException raise:@"SUAppcastException" format:@"Couldn't find a version string for %@! You need a sparkle:version attribute.", [enclosure objectForKey:@"url"]];
|
||||
}
|
||||
[self setVersionString:newVersion];
|
||||
[self setMinimumSystemVersion:[dict objectForKey:@"sparkle:minimumSystemVersion"]];
|
||||
|
||||
if(!newVersion )
|
||||
{
|
||||
if (error)
|
||||
*error = @"Feed item lacks sparkle:version attribute, and version couldn't be deduced from file name (would have used last component of a file name like AppName_1.3.4.zip)";
|
||||
[self release];
|
||||
return nil;
|
||||
}
|
||||
|
||||
propertiesDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict];
|
||||
[self setTitle:[dict objectForKey:@"title"]];
|
||||
[self setDate:[dict objectForKey:@"pubDate"]];
|
||||
[self setItemDescription:[dict objectForKey:@"description"]];
|
||||
|
||||
NSString* theInfoURL = [dict objectForKey:@"link"];
|
||||
if( theInfoURL )
|
||||
{
|
||||
if( ![theInfoURL isKindOfClass: [NSString class]] )
|
||||
SULog(@"SUAppcastItem -initWithDictionary: Info URL is not of valid type.");
|
||||
else
|
||||
[self setInfoURL:[NSURL URLWithString:theInfoURL]];
|
||||
}
|
||||
|
||||
// Need an info URL or an enclosure URL. Former to show "More Info"
|
||||
// page, latter to download & install:
|
||||
if( !enclosure && !theInfoURL )
|
||||
{
|
||||
if (error)
|
||||
*error = @"No enclosure in feed item";
|
||||
[self release];
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString* enclosureURLString = [enclosure objectForKey:@"url"];
|
||||
if( !enclosureURLString && !theInfoURL )
|
||||
{
|
||||
if (error)
|
||||
*error = @"Feed item's enclosure lacks URL";
|
||||
[self release];
|
||||
return nil;
|
||||
}
|
||||
|
||||
if( enclosureURLString )
|
||||
[self setFileURL: [NSURL URLWithString: [enclosureURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
|
||||
if( enclosure )
|
||||
[self setDSASignature:[enclosure objectForKey:@"sparkle:dsaSignature"]];
|
||||
|
||||
[self setVersionString: newVersion];
|
||||
[self setMinimumSystemVersion: [dict objectForKey:@"sparkle:minimumSystemVersion"]];
|
||||
[self setMaximumSystemVersion: [dict objectForKey:@"sparkle:maximumSystemVersion"]];
|
||||
|
||||
NSString *shortVersionString = [enclosure objectForKey:@"sparkle:shortVersionString"];
|
||||
if (nil == shortVersionString)
|
||||
shortVersionString = [dict objectForKey:@"sparkle:shortVersionString"]; // fall back on the <item>
|
||||
|
||||
if (shortVersionString)
|
||||
[self setDisplayVersionString:shortVersionString];
|
||||
[self setDisplayVersionString: shortVersionString];
|
||||
else
|
||||
[self setDisplayVersionString:[self versionString]];
|
||||
[self setDisplayVersionString: [self versionString]];
|
||||
|
||||
// Find the appropriate release notes URL.
|
||||
if ([dict objectForKey:@"sparkle:releaseNotesLink"])
|
||||
[self setReleaseNotesURL:[NSURL URLWithString:[dict objectForKey:@"sparkle:releaseNotesLink"]]];
|
||||
else if ([[self description] hasPrefix:@"http://"]) // if the description starts with http://, use that.
|
||||
[self setReleaseNotesURL:[NSURL URLWithString:[self description]]];
|
||||
else if ([[self itemDescription] hasPrefix:@"http://"] || [[self itemDescription] hasPrefix:@"https://"]) // if the description starts with http:// or https:// use that.
|
||||
[self setReleaseNotesURL:[NSURL URLWithString:[self itemDescription]]];
|
||||
else
|
||||
[self setReleaseNotesURL:nil];
|
||||
|
||||
if ([dict objectForKey:@"deltas"])
|
||||
{
|
||||
NSMutableDictionary *deltas = [NSMutableDictionary dictionary];
|
||||
NSArray *deltaDictionaries = [dict objectForKey:@"deltas"];
|
||||
NSEnumerator *deltaDictionariesEnum = [deltaDictionaries objectEnumerator];
|
||||
NSDictionary *deltaDictionary;
|
||||
while ((deltaDictionary = [deltaDictionariesEnum nextObject]))
|
||||
{
|
||||
NSMutableDictionary *fakeAppCastDict = [dict mutableCopy];
|
||||
[fakeAppCastDict removeObjectForKey:@"deltas"];
|
||||
[fakeAppCastDict setObject:deltaDictionary forKey:@"enclosure"];
|
||||
SUAppcastItem *deltaItem = [[[self class] alloc] initWithDictionary:fakeAppCastDict];
|
||||
[fakeAppCastDict release];
|
||||
|
||||
[deltas setObject:deltaItem forKey:[deltaDictionary objectForKey:@"sparkle:deltaFrom"]];
|
||||
[deltaItem release];
|
||||
}
|
||||
[self setDeltaUpdates:deltas];
|
||||
}
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@@ -160,12 +264,14 @@
|
||||
{
|
||||
[self setTitle:nil];
|
||||
[self setDate:nil];
|
||||
[self setDescription:nil];
|
||||
[self setItemDescription:nil];
|
||||
[self setReleaseNotesURL:nil];
|
||||
[self setDSASignature:nil];
|
||||
[self setMinimumSystemVersion: nil];
|
||||
[self setFileURL:nil];
|
||||
[self setVersionString:nil];
|
||||
[self setDisplayVersionString:nil];
|
||||
[self setInfoURL:nil];
|
||||
[propertiesDictionary release];
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
@@ -18,14 +18,14 @@ typedef enum
|
||||
SUDoNotInstallChoice
|
||||
} SUAutomaticInstallationChoice;
|
||||
|
||||
@class SUAppcastItem;
|
||||
@class SUAppcastItem, SUHost;
|
||||
@interface SUAutomaticUpdateAlert : SUWindowController {
|
||||
SUAppcastItem *updateItem;
|
||||
id delegate;
|
||||
NSBundle *hostBundle;
|
||||
SUHost *host;
|
||||
}
|
||||
|
||||
- (id)initWithAppcastItem:(SUAppcastItem *)item hostBundle:(NSBundle *)hostBundle delegate:delegate;
|
||||
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)hostBundle delegate:delegate;
|
||||
- (IBAction)installNow:sender;
|
||||
- (IBAction)installLater:sender;
|
||||
- (IBAction)doNotInstall:sender;
|
||||
|
||||
@@ -6,19 +6,20 @@
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "SUAutomaticUpdateAlert.h"
|
||||
|
||||
#import "SUHost.h"
|
||||
|
||||
@implementation SUAutomaticUpdateAlert
|
||||
|
||||
- (id)initWithAppcastItem:(SUAppcastItem *)item hostBundle:(NSBundle *)hb delegate:del;
|
||||
- (id)initWithAppcastItem:(SUAppcastItem *)item host:(SUHost *)aHost delegate:del;
|
||||
{
|
||||
self = [super initWithHostBundle:hb windowNibName:@"SUAutomaticUpdateAlert"];
|
||||
self = [super initWithHost:aHost windowNibName:@"SUAutomaticUpdateAlert"];
|
||||
if (self)
|
||||
{
|
||||
updateItem = [item retain];
|
||||
delegate = del;
|
||||
hostBundle = [hb retain];
|
||||
host = [aHost retain];
|
||||
[self setShouldCascadeWindows:NO];
|
||||
[[self window] center];
|
||||
}
|
||||
@@ -27,11 +28,12 @@
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[hostBundle release];
|
||||
[host release];
|
||||
[updateItem release];
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [host bundlePath], [host installationPath]]; }
|
||||
|
||||
- (IBAction)installNow:sender
|
||||
{
|
||||
@@ -53,17 +55,17 @@
|
||||
|
||||
- (NSImage *)applicationIcon
|
||||
{
|
||||
return [hostBundle icon];
|
||||
return [host icon];
|
||||
}
|
||||
|
||||
- (NSString *)titleText
|
||||
{
|
||||
return [NSString stringWithFormat:SULocalizedString(@"A new version of %@ is ready to install!", nil), [hostBundle name]];
|
||||
return [NSString stringWithFormat:SULocalizedString(@"A new version of %@ is ready to install!", nil), [host name]];
|
||||
}
|
||||
|
||||
- (NSString *)descriptionText
|
||||
{
|
||||
return [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?", nil), [hostBundle name], [hostBundle displayVersion]];
|
||||
return [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?", nil), [host name], [updateItem displayVersionString]];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -13,7 +13,9 @@
|
||||
#import "SUBasicUpdateDriver.h"
|
||||
|
||||
@class SUAutomaticUpdateAlert;
|
||||
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver {
|
||||
@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver
|
||||
{
|
||||
@private
|
||||
BOOL postponingInstallation, showErrors;
|
||||
SUAutomaticUpdateAlert *alert;
|
||||
}
|
||||
|
||||
+62
-15
@@ -7,13 +7,67 @@
|
||||
//
|
||||
|
||||
#import "SUAutomaticUpdateDriver.h"
|
||||
#import "Sparkle.h"
|
||||
|
||||
#import "SUAutomaticUpdateAlert.h"
|
||||
#import "SUHost.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SUUpdater_Private.h"
|
||||
#import "SUXPCURLDownload.h"
|
||||
|
||||
@implementation SUAutomaticUpdateDriver
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
#if SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
|
||||
|
||||
static NSString * const kSUAutomaticUpdateParamName = @"autoupdate";
|
||||
|
||||
- (void)downloadReleaseNotesAndWaitUntilDone
|
||||
{
|
||||
NSURL *releaseNotesURL = [updateItem releaseNotesURL];
|
||||
if (nil == releaseNotesURL || [releaseNotesURL isFileURL])
|
||||
return;
|
||||
|
||||
NSString *URLString = [releaseNotesURL absoluteString];
|
||||
URLString = [URLString stringByAppendingFormat:@"%@%@=1", ([releaseNotesURL query] != nil) ? @"&" : @"?", kSUAutomaticUpdateParamName];
|
||||
releaseNotesURL = [NSURL URLWithString:URLString];
|
||||
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:releaseNotesURL];
|
||||
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
|
||||
[self updateURLRequestIfNeeds:request];
|
||||
|
||||
if ([SUUpdater shouldUseXPCDownloader])
|
||||
{
|
||||
[SUXPCURLDownload sendSynchronousRequest:request delegate:nil];
|
||||
}
|
||||
else
|
||||
{
|
||||
[NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)didFindValidUpdate
|
||||
{
|
||||
// For correct DevMate statistics need to send request for Release Notes.
|
||||
[self downloadReleaseNotesAndWaitUntilDone];
|
||||
[super didFindValidUpdate];
|
||||
}
|
||||
|
||||
#endif // SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
- (void)unarchiverDidFinish:(SUUnarchiver *)ua
|
||||
{
|
||||
alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:updateItem hostBundle:hostBundle delegate:self];
|
||||
alert = [[SUAutomaticUpdateAlert alloc] initWithAppcastItem:updateItem host:host delegate:self];
|
||||
|
||||
// If the app is a menubar app or the like, we need to focus it first and alter the
|
||||
// update prompt to behave like a normal window. Otherwise if the window were hidden
|
||||
// there may be no way for the application to be activated to make it visible again.
|
||||
if ([host isBackgroundApplication])
|
||||
{
|
||||
[[alert window] setHidesOnDeactivate:NO];
|
||||
[NSApp activateIgnoringOtherApps:YES];
|
||||
}
|
||||
|
||||
if ([NSApp isActive])
|
||||
[[alert window] makeKeyAndOrderFront:self];
|
||||
else
|
||||
@@ -23,7 +77,7 @@
|
||||
- (void)applicationDidBecomeActive:(NSNotification *)aNotification
|
||||
{
|
||||
[[alert window] makeKeyAndOrderFront:self];
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSApplicationDidBecomeActiveNotification" object:NSApp];
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidBecomeActiveNotification object:NSApp];
|
||||
}
|
||||
|
||||
- (void)automaticUpdateAlert:(SUAutomaticUpdateAlert *)aua finishedWithChoice:(SUAutomaticInstallationChoice)choice;
|
||||
@@ -31,7 +85,7 @@
|
||||
switch (choice)
|
||||
{
|
||||
case SUInstallNowChoice:
|
||||
[self installUpdate];
|
||||
[self installWithToolAndRelaunch:YES];
|
||||
break;
|
||||
|
||||
case SUInstallLaterChoice:
|
||||
@@ -40,7 +94,7 @@
|
||||
break;
|
||||
|
||||
case SUDoNotInstallChoice:
|
||||
[[SUUserDefaults standardUserDefaults] setObject:[updateItem versionString] forKey:SUSkippedVersionKey];
|
||||
[host setObject:[updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey];
|
||||
[self abortUpdate];
|
||||
break;
|
||||
}
|
||||
@@ -48,22 +102,15 @@
|
||||
|
||||
- (BOOL)shouldInstallSynchronously { return postponingInstallation; }
|
||||
|
||||
- (void)installUpdate
|
||||
- (void)installWithToolAndRelaunch:(BOOL)relaunch
|
||||
{
|
||||
showErrors = YES;
|
||||
[super installUpdate];
|
||||
[super installWithToolAndRelaunch:relaunch];
|
||||
}
|
||||
|
||||
- (void)applicationWillTerminate:(NSNotification *)note
|
||||
{
|
||||
[self installUpdate];
|
||||
}
|
||||
|
||||
- (void)installerFinishedForHostBundle:(NSBundle *)hb
|
||||
{
|
||||
if (hb != hostBundle) { return; }
|
||||
if (!postponingInstallation)
|
||||
[self relaunchHostApp];
|
||||
[self installWithToolAndRelaunch:NO];
|
||||
}
|
||||
|
||||
- (void)abortUpdateWithError:(NSError *)error
|
||||
|
||||
+10
-8
@@ -12,18 +12,19 @@
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUUpdateDriver.h"
|
||||
|
||||
@class SUAppcastItem, SUUnarchiver, SUAppcast, SUUnarchiver;
|
||||
@class SUAppcastItem, SUUnarchiver, SUAppcast, SUUnarchiver, SUHost;
|
||||
@interface SUBasicUpdateDriver : SUUpdateDriver {
|
||||
NSBundle *hostBundle;
|
||||
SUAppcastItem *updateItem;
|
||||
SUAppcastItem *nonDeltaUpdateItem;
|
||||
|
||||
NSURLDownload *download;
|
||||
NSString *downloadPath;
|
||||
NSString *tempDir;
|
||||
|
||||
NSString *relaunchPath;
|
||||
}
|
||||
|
||||
- (void)checkForUpdatesAtURL:(NSURL *)appcastURL hostBundle:(NSBundle *)hb;
|
||||
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)host;
|
||||
|
||||
- (void)appcastDidFinishLoading:(SUAppcast *)ac;
|
||||
- (void)appcast:(SUAppcast *)ac failedToLoadWithError:(NSError *)error;
|
||||
@@ -35,6 +36,7 @@
|
||||
- (void)didFindValidUpdate;
|
||||
- (void)didNotFindUpdate;
|
||||
|
||||
- (void)updateURLRequestIfNeeds:(NSMutableURLRequest *)request;
|
||||
- (void)downloadUpdate;
|
||||
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name;
|
||||
- (void)downloadDidFinish:(NSURLDownload *)d;
|
||||
@@ -43,13 +45,13 @@
|
||||
- (void)extractUpdate;
|
||||
- (void)unarchiverDidFinish:(SUUnarchiver *)ua;
|
||||
- (void)unarchiverDidFail:(SUUnarchiver *)ua;
|
||||
- (void)failedToApplyDeltaUpdate;
|
||||
|
||||
- (void)installUpdate;
|
||||
- (void)installerFinishedForHostBundle:(NSBundle *)hb;
|
||||
- (void)installerForHostBundle:(NSBundle *)hb failedWithError:(NSError *)error;
|
||||
- (void)installWithToolAndRelaunch:(BOOL)relaunch;
|
||||
- (void)installerForHost:(SUHost *)host failedWithError:(NSError *)error;
|
||||
|
||||
- (void)relaunchHostApp;
|
||||
- (void)cleanUp;
|
||||
- (void)installWithToolAndRelaunch:(BOOL)relaunch;
|
||||
- (void)cleanUpDownload;
|
||||
|
||||
- (void)abortUpdate;
|
||||
- (void)abortUpdateWithError:(NSError *)error;
|
||||
|
||||
+338
-120
@@ -7,17 +7,52 @@
|
||||
//
|
||||
|
||||
#import "SUBasicUpdateDriver.h"
|
||||
#import "Sparkle.h"
|
||||
|
||||
#import "SUHost.h"
|
||||
#import "SUDSAVerifier.h"
|
||||
#import "SUInstaller.h"
|
||||
#import "SUStandardVersionComparator.h"
|
||||
#import "SUUnarchiver.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SULog.h"
|
||||
#import "SUPlainInstaller.h"
|
||||
#import "SUPlainInstallerInternals.h"
|
||||
#import "SUBinaryDeltaCommon.h"
|
||||
#import "SUCodeSigningVerifier.h"
|
||||
#import "SUUpdater_Private.h"
|
||||
#import "SUXPCInstaller.h"
|
||||
#import "SUXPCURLDownload.h"
|
||||
|
||||
#if SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
|
||||
CF_EXPORT CFDictionaryRef DMCopyHTTPRequestHeaders(CFBundleRef appBundle, CFDataRef httpBodyData);
|
||||
|
||||
NSArray *SUGetAllDevMateURLHosts(void);
|
||||
NSArray *SUGetAllDevMateURLHosts(void)
|
||||
{
|
||||
static NSArray *sAllKnownDevMateURLHosts = nil;
|
||||
if (nil == sAllKnownDevMateURLHosts)
|
||||
{
|
||||
sAllKnownDevMateURLHosts = [[NSArray alloc] initWithObjects:
|
||||
@"updates.devmate.com",
|
||||
@"test.updates.aws.devmate.vpn",
|
||||
nil];
|
||||
}
|
||||
|
||||
return sAllKnownDevMateURLHosts;
|
||||
}
|
||||
#endif
|
||||
|
||||
@interface SUBasicUpdateDriver () <NSURLDownloadDelegate>; @end
|
||||
|
||||
|
||||
@implementation SUBasicUpdateDriver
|
||||
|
||||
- (void)checkForUpdatesAtURL:(NSURL *)appcastURL hostBundle:(NSBundle *)hb
|
||||
- (void)checkForUpdatesAtURL:(NSURL *)URL host:(SUHost *)aHost
|
||||
{
|
||||
hostBundle = [hb retain];
|
||||
|
||||
if ([hostBundle isRunningFromDiskImage])
|
||||
[super checkForUpdatesAtURL:URL host:aHost];
|
||||
if ([aHost isRunningOnReadOnlyVolume])
|
||||
{
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated when it's running from a disk image. Move %1$@ to your Applications folder, relaunch it from there, and try again.", nil), [hostBundle name]] forKey:NSLocalizedDescriptionKey]]];
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:SULocalizedString(@"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again.", nil), [aHost name]] forKey:NSLocalizedDescriptionKey]]];
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -26,29 +61,54 @@
|
||||
[appcast release];
|
||||
|
||||
[appcast setDelegate:self];
|
||||
[appcast setUserAgentString:[NSString stringWithFormat: @"%@/%@ Sparkle/1.5b2", [hostBundle name], [hostBundle displayVersion]]];
|
||||
[appcast fetchAppcastFromURL:appcastURL];
|
||||
[appcast setUserAgentString:[updater userAgentString]];
|
||||
[appcast fetchAppcastFromURL:URL];
|
||||
}
|
||||
|
||||
- (id <SUVersionComparison>)versionComparator
|
||||
{
|
||||
id <SUVersionComparison> comparator = nil;
|
||||
|
||||
// Give the delegate a chance to provide a custom version comparator
|
||||
if ([[updater delegate] respondsToSelector:@selector(versionComparatorForUpdater:)])
|
||||
comparator = [[updater delegate] versionComparatorForUpdater:updater];
|
||||
|
||||
// If we don't get a comparator from the delegate, use the default comparator
|
||||
if (!comparator)
|
||||
comparator = [SUStandardVersionComparator defaultComparator];
|
||||
|
||||
return comparator;
|
||||
}
|
||||
|
||||
- (BOOL)isItemNewer:(SUAppcastItem *)ui
|
||||
{
|
||||
return [[SUStandardVersionComparator defaultComparator] compareVersion:[hostBundle version]
|
||||
toVersion:[ui versionString]] == NSOrderedAscending;
|
||||
return [[self versionComparator] compareVersion:[host version] toVersion:[ui versionString]] == NSOrderedAscending;
|
||||
}
|
||||
|
||||
- (BOOL)hostSupportsItem:(SUAppcastItem *)ui
|
||||
{
|
||||
if ([ui minimumSystemVersion] == nil || [[ui minimumSystemVersion] isEqualToString:@""]) { return YES; }
|
||||
return [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion]
|
||||
toVersion:[NSWorkspace systemVersionString]] != NSOrderedDescending;
|
||||
if (([ui minimumSystemVersion] == nil || [[ui minimumSystemVersion] isEqualToString:@""]) &&
|
||||
([ui maximumSystemVersion] == nil || [[ui maximumSystemVersion] isEqualToString:@""])) { return YES; }
|
||||
|
||||
BOOL minimumVersionOK = TRUE;
|
||||
BOOL maximumVersionOK = TRUE;
|
||||
|
||||
// Check minimum and maximum System Version
|
||||
if ([ui minimumSystemVersion] != nil && ![[ui minimumSystemVersion] isEqualToString:@""]) {
|
||||
minimumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui minimumSystemVersion] toVersion:[SUHost systemVersionString]] != NSOrderedDescending;
|
||||
}
|
||||
if ([ui maximumSystemVersion] != nil && ![[ui maximumSystemVersion] isEqualToString:@""]) {
|
||||
maximumVersionOK = [[SUStandardVersionComparator defaultComparator] compareVersion:[ui maximumSystemVersion] toVersion:[SUHost systemVersionString]] != NSOrderedAscending;
|
||||
}
|
||||
|
||||
return minimumVersionOK && maximumVersionOK;
|
||||
}
|
||||
|
||||
- (BOOL)itemContainsSkippedVersion:(SUAppcastItem *)ui
|
||||
{
|
||||
NSString *skippedVersion = [[SUUserDefaults standardUserDefaults] objectForKey:SUSkippedVersionKey];
|
||||
NSString *skippedVersion = [host objectForUserDefaultsKey:SUSkippedVersionKey];
|
||||
if (skippedVersion == nil) { return NO; }
|
||||
return [[SUStandardVersionComparator defaultComparator] compareVersion:[ui versionString]
|
||||
toVersion:skippedVersion] != NSOrderedDescending;
|
||||
return [[self versionComparator] compareVersion:[ui versionString] toVersion:skippedVersion] != NSOrderedDescending;
|
||||
}
|
||||
|
||||
- (BOOL)itemContainsValidUpdate:(SUAppcastItem *)ui
|
||||
@@ -58,29 +118,35 @@
|
||||
|
||||
- (void)appcastDidFinishLoading:(SUAppcast *)ac
|
||||
{
|
||||
if ([delegate respondsToSelector:@selector(appcastDidFinishLoading:forHostBundle:)])
|
||||
[delegate appcastDidFinishLoading:ac forHostBundle:hostBundle];
|
||||
|
||||
NSArray* updates = [ac items];
|
||||
if ([updates count] > 0)
|
||||
[[SUUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:SULastCheckTimeKey];
|
||||
|
||||
if ([[updater delegate] respondsToSelector:@selector(updater:didFinishLoadingAppcast:)])
|
||||
[[updater delegate] updater:updater didFinishLoadingAppcast:ac];
|
||||
|
||||
SUAppcastItem *item = nil;
|
||||
|
||||
// Now we have to find the best valid update in the appcast.
|
||||
if ([delegate respondsToSelector:@selector(bestValidUpdateInAppcast:forHostBundle:)]) // Does the delegate want to handle it?
|
||||
if ([[updater delegate] respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) // Does the delegate want to handle it?
|
||||
{
|
||||
updateItem = [delegate bestValidUpdateInAppcast:ac forHostBundle:hostBundle];
|
||||
item = [[updater delegate] bestValidUpdateInAppcast:ac forUpdater:updater];
|
||||
}
|
||||
else // If not, we'll take care of it ourselves.
|
||||
{
|
||||
// Find the first update we can actually use.
|
||||
NSEnumerator *updateEnumerator = [updates objectEnumerator];
|
||||
NSEnumerator *updateEnumerator = [[ac items] objectEnumerator];
|
||||
do {
|
||||
updateItem = [updateEnumerator nextObject];
|
||||
} while (updateItem && ![self hostSupportsItem:updateItem]);
|
||||
|
||||
[updateItem retain];
|
||||
item = [updateEnumerator nextObject];
|
||||
} while (item && ![self hostSupportsItem:item]);
|
||||
|
||||
if (binaryDeltaSupported()) {
|
||||
SUAppcastItem *deltaUpdateItem = [[item deltaUpdates] objectForKey:[host version]];
|
||||
if (deltaUpdateItem && [self hostSupportsItem:deltaUpdateItem]) {
|
||||
nonDeltaUpdateItem = [item retain];
|
||||
item = deltaUpdateItem;
|
||||
}
|
||||
}
|
||||
}
|
||||
CFRelease(ac); // Remember that we're explicitly managing the memory of the appcast.
|
||||
|
||||
updateItem = [item retain];
|
||||
if (ac) { CFRelease(ac); } // Remember that we're explicitly managing the memory of the appcast.
|
||||
if (updateItem == nil) { [self didNotFindUpdate]; return; }
|
||||
|
||||
if ([self itemContainsValidUpdate:updateItem])
|
||||
@@ -91,46 +157,99 @@
|
||||
|
||||
- (void)appcast:(SUAppcast *)ac failedToLoadWithError:(NSError *)error
|
||||
{
|
||||
CFRelease(ac); // Remember that we're explicitly managing the memory of the appcast.
|
||||
if (ac) { CFRelease(ac); } // Remember that we're explicitly managing the memory of the appcast.
|
||||
[self abortUpdateWithError:error];
|
||||
}
|
||||
|
||||
- (void)appcast:(SUAppcast *)appcast willFetchURLRequest:(NSMutableURLRequest *)request
|
||||
{
|
||||
[self updateURLRequestIfNeeds:request];
|
||||
}
|
||||
|
||||
- (void)updateURLRequestIfNeeds:(NSMutableURLRequest *)request
|
||||
{
|
||||
#if SPARKLE_IS_COMPATIBLE_WITH_DEVMATE
|
||||
if ([SUGetAllDevMateURLHosts() containsObject:[[request URL] host]])
|
||||
{
|
||||
CFBundleRef hostBundle = CFBundleCreate(kCFAllocatorDefault, (CFURLRef)[NSURL fileURLWithPath:[host bundlePath]]);
|
||||
NSDictionary *devmateHeaders = (NSDictionary *)DMCopyHTTPRequestHeaders(hostBundle, NULL) ? : [NSDictionary new];
|
||||
[request setAllHTTPHeaderFields:(NSDictionary *)devmateHeaders];
|
||||
|
||||
[devmateHeaders release];
|
||||
if (NULL != hostBundle)
|
||||
CFRelease(hostBundle);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
- (void)didFindValidUpdate
|
||||
{
|
||||
if ([delegate respondsToSelector:@selector(didFindValidUpdate:toHostBundle:)])
|
||||
[delegate didFindValidUpdate:updateItem toHostBundle:hostBundle];
|
||||
if ([[updater delegate] respondsToSelector:@selector(updater:didFindValidUpdate:)])
|
||||
[[updater delegate] updater:updater didFindValidUpdate:updateItem];
|
||||
[self downloadUpdate];
|
||||
}
|
||||
|
||||
- (void)didNotFindUpdate
|
||||
{
|
||||
if ([delegate respondsToSelector:@selector(didNotFindUpdateToHostBundle:)])
|
||||
[delegate didNotFindUpdateToHostBundle:hostBundle];
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUNoUpdateError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:SULocalizedString(@"You already have the newest version of %@.", nil), [hostBundle name]] forKey:NSLocalizedDescriptionKey]]];
|
||||
if ([[updater delegate] respondsToSelector:@selector(updaterDidNotFindUpdate:)])
|
||||
[[updater delegate] updaterDidNotFindUpdate:updater];
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUNoUpdateError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:SULocalizedString(@"You already have the newest version of %@.", nil), [host name]] forKey:NSLocalizedDescriptionKey]]];
|
||||
}
|
||||
|
||||
- (void)downloadUpdate
|
||||
{
|
||||
download = [[NSURLDownload alloc] initWithRequest:[NSURLRequest requestWithURL:[updateItem fileURL]] delegate:self];
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[updateItem fileURL]];
|
||||
[request setValue:[updater userAgentString] forHTTPHeaderField:@"User-Agent"];
|
||||
[self updateURLRequestIfNeeds:request];
|
||||
|
||||
if ([SUUpdater shouldUseXPCDownloader])
|
||||
download = (NSURLDownload *)[[SUXPCURLDownload alloc] initWithRequest:request delegate:self];
|
||||
else
|
||||
download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)d decideDestinationWithSuggestedFilename:(NSString *)name
|
||||
{
|
||||
if ([SUUpdater shouldUseXPCDownloader]) {
|
||||
// The downloader will determine a file name, somewhere within our sandbox.
|
||||
downloadPath = nil;
|
||||
[d setDestination:name allowOverwrite:YES];
|
||||
return;
|
||||
}
|
||||
|
||||
// If name ends in .txt, the server probably has a stupid MIME configuration. We'll give the developer the benefit of the doubt and chop that off.
|
||||
if ([[name pathExtension] isEqualToString:@"txt"])
|
||||
name = [name stringByDeletingPathExtension];
|
||||
|
||||
// We create a temporary directory in /tmp and stick the file there.
|
||||
// Not using a GUID here because hdiutil for some reason chokes on GUIDs. Too long? I really have no idea.
|
||||
NSString *prefix = [NSString stringWithFormat:@"%@ %@ Update", [hostBundle name], [hostBundle version]];
|
||||
NSString *tempDir = [NSTemporaryDirectory() stringByAppendingPathComponent:prefix];
|
||||
NSString *downloadFileName = [NSString stringWithFormat:@"%@ %@", [host name], [updateItem versionString]];
|
||||
|
||||
|
||||
[tempDir release];
|
||||
tempDir = [[[host appSupportPath] stringByAppendingPathComponent:downloadFileName] retain];
|
||||
int cnt=1;
|
||||
while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 999999)
|
||||
tempDir = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", prefix, cnt++]];
|
||||
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:tempDir attributes:nil];
|
||||
while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 999)
|
||||
{
|
||||
[tempDir release];
|
||||
tempDir = [[[host appSupportPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, cnt++]] retain];
|
||||
}
|
||||
|
||||
// Create the temporary directory if necessary.
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
|
||||
BOOL success = YES;
|
||||
NSEnumerator *pathComponentEnumerator = [[tempDir pathComponents] objectEnumerator];
|
||||
NSString *pathComponentAccumulator = @"";
|
||||
NSString *currentPathComponent;
|
||||
while ((currentPathComponent = [pathComponentEnumerator nextObject])) {
|
||||
pathComponentAccumulator = [pathComponentAccumulator stringByAppendingPathComponent:currentPathComponent];
|
||||
if ([[NSFileManager defaultManager] fileExistsAtPath:pathComponentAccumulator]) continue;
|
||||
success &= [[NSFileManager defaultManager] createDirectoryAtPath:pathComponentAccumulator attributes:nil];
|
||||
}
|
||||
#else
|
||||
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:tempDir withIntermediateDirectories:YES attributes:nil error:NULL];
|
||||
#endif
|
||||
if (!success)
|
||||
{
|
||||
// Okay, something's really broken with /tmp
|
||||
// Okay, something's really broken with this user's file structure.
|
||||
[download cancel];
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.",tempDir] forKey:NSLocalizedDescriptionKey]]];
|
||||
}
|
||||
@@ -139,35 +258,52 @@
|
||||
[download setDestination:downloadPath allowOverwrite:YES];
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish:(NSURLDownload *)d
|
||||
- (void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path {
|
||||
[downloadPath autorelease];
|
||||
downloadPath = [path retain];
|
||||
[tempDir autorelease];
|
||||
tempDir = [[downloadPath stringByDeletingLastPathComponent] retain];
|
||||
}
|
||||
|
||||
- (BOOL)validateUpdateDownloadedToPath:(NSString *)downloadedPath extractedToPath:(NSString *)extractedPath DSASignature:(NSString *)DSASignature publicDSAKey:(NSString *)publicDSAKey
|
||||
{
|
||||
NSString *newBundlePath = [SUInstaller appPathInUpdateFolder:extractedPath forHost:host];
|
||||
if (newBundlePath)
|
||||
{
|
||||
NSError *error = nil;
|
||||
if ([SUCodeSigningVerifier codeSignatureIsValidAtPath:newBundlePath error:&error]) {
|
||||
return YES;
|
||||
} else {
|
||||
SULog(@"Code signature check on update failed: %@", error);
|
||||
}
|
||||
}
|
||||
|
||||
return [SUDSAVerifier validatePath:downloadedPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey];
|
||||
}
|
||||
|
||||
- (void)downloadDidFinish:(NSURLDownload *)d
|
||||
{
|
||||
[self extractUpdate];
|
||||
}
|
||||
|
||||
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
|
||||
{
|
||||
// Get rid of what we've downloaded so far, if anything.
|
||||
if (downloadPath != nil)
|
||||
[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[downloadPath stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[downloadPath lastPathComponent]] tag:NULL];
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), NSLocalizedDescriptionKey, [error localizedDescription], NSLocalizedFailureReasonErrorKey, nil]]];
|
||||
}
|
||||
|
||||
- (BOOL)download:(NSURLDownload *)download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
|
||||
{
|
||||
// We don't want the download system to extract our gzips.
|
||||
// Note that we use a substring matching here instead of direct comparison because the docs say "application/gzip" but the system *uses* "application/x-gzip". This is a documentation bug.
|
||||
return ([encodingType rangeOfString:@"gzip"].location == NSNotFound);
|
||||
}
|
||||
|
||||
- (void)extractUpdate
|
||||
{
|
||||
// DSA verification, if activated by the developer
|
||||
if ([[hostBundle objectForInfoDictionaryKey:SUExpectsDSASignatureKey] boolValue])
|
||||
{
|
||||
if (![[NSFileManager defaultManager] validatePath:downloadPath withEncodedDSASignature:[updateItem DSASignature] withPublicDSAKey:[hostBundle publicDSAKey]])
|
||||
{
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:[NSDictionary dictionaryWithObject:@"The update is improperly signed." forKey:NSLocalizedDescriptionKey]]];
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForURL:[[[NSURL alloc] initFileURLWithPath:downloadPath] autorelease]];
|
||||
SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:downloadPath updatingHost:host];
|
||||
if (!unarchiver)
|
||||
{
|
||||
NSLog(@"Sparkle Error: No valid unarchiver for %@!", downloadPath);
|
||||
SULog(@"Sparkle Error: No valid unarchiver for %@!", downloadPath);
|
||||
[self unarchiverDidFail:nil];
|
||||
return;
|
||||
}
|
||||
@@ -176,88 +312,165 @@
|
||||
[unarchiver start];
|
||||
}
|
||||
|
||||
- (void)failedToApplyDeltaUpdate
|
||||
{
|
||||
// When a delta update fails to apply we fall back on updating via a full install.
|
||||
[updateItem release];
|
||||
updateItem = nonDeltaUpdateItem;
|
||||
nonDeltaUpdateItem = nil;
|
||||
|
||||
[self downloadUpdate];
|
||||
}
|
||||
|
||||
- (void)unarchiverDidFinish:(SUUnarchiver *)ua
|
||||
{
|
||||
if (ua) { CFRelease(ua); }
|
||||
[self installUpdate];
|
||||
[self installWithToolAndRelaunch:YES];
|
||||
}
|
||||
|
||||
- (void)unarchiverDidFail:(SUUnarchiver *)ua
|
||||
{
|
||||
if (ua) { CFRelease(ua); }
|
||||
|
||||
if ([updateItem isDeltaUpdate]) {
|
||||
[self failedToApplyDeltaUpdate];
|
||||
return;
|
||||
}
|
||||
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:[NSDictionary dictionaryWithObject:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) forKey:NSLocalizedDescriptionKey]]];
|
||||
}
|
||||
|
||||
- (BOOL)shouldInstallSynchronously { return NO; }
|
||||
|
||||
- (void)installUpdate
|
||||
- (void)installWithToolAndRelaunch:(BOOL)relaunch
|
||||
{
|
||||
if ([delegate respondsToSelector:@selector(updateWillInstall:toHostBundle:)])
|
||||
[delegate updateWillInstall:updateItem toHostBundle:hostBundle];
|
||||
// Copy the relauncher into a temporary directory so we can get to it after the new version's installed.
|
||||
NSString *relaunchPathToCopy = [[NSBundle bundleForClass:[self class]] pathForResource:@"relaunch" ofType:@""];
|
||||
NSString *targetPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]];
|
||||
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems
|
||||
[[NSFileManager defaultManager] removeFileAtPath:targetPath handler:nil];
|
||||
if ([[NSFileManager defaultManager] copyPath:relaunchPathToCopy toPath:targetPath handler:nil])
|
||||
relaunchPath = [targetPath retain];
|
||||
|
||||
[SUInstaller installFromUpdateFolder:[downloadPath stringByDeletingLastPathComponent] overHostBundle:hostBundle delegate:self synchronously:[self shouldInstallSynchronously]];
|
||||
}
|
||||
|
||||
- (void)installerFinishedForHostBundle:(NSBundle *)hb
|
||||
{
|
||||
if (hb != hostBundle) { return; }
|
||||
[self relaunchHostApp];
|
||||
}
|
||||
|
||||
- (void)relaunchHostApp
|
||||
{
|
||||
// Give the host app an opportunity to postpone the relaunch.
|
||||
static BOOL postponedOnce = NO;
|
||||
if (!postponedOnce && [delegate respondsToSelector:@selector(shouldPostponeRelaunchForUpdate:toHostBundle:untilInvoking:)])
|
||||
{
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[[self class] instanceMethodSignatureForSelector:@selector(relaunchHostApp)] retain]];
|
||||
[invocation setSelector:@selector(relaunchHostApp)];
|
||||
[invocation setTarget:self];
|
||||
postponedOnce = YES;
|
||||
if ([delegate shouldPostponeRelaunchForUpdate:updateItem toHostBundle:hostBundle untilInvoking:invocation])
|
||||
return;
|
||||
#if !ENDANGER_USERS_WITH_INSECURE_UPDATES
|
||||
if (![self validateUpdateDownloadedToPath:downloadPath extractedToPath:tempDir DSASignature:[updateItem DSASignature] publicDSAKey:[host publicDSAKey]])
|
||||
{
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUSignatureError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), NSLocalizedDescriptionKey, @"The update is improperly signed.", NSLocalizedFailureReasonErrorKey, nil]]];
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (![updater mayUpdateAndRestart])
|
||||
{
|
||||
[self abortUpdate];
|
||||
return;
|
||||
}
|
||||
|
||||
// Give the host app an opportunity to postpone the install and relaunch.
|
||||
static BOOL postponedOnce = NO;
|
||||
if (!postponedOnce && [[updater delegate] respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:untilInvoking:)])
|
||||
{
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(installWithToolAndRelaunch:)]];
|
||||
[invocation setSelector:@selector(installWithToolAndRelaunch:)];
|
||||
[invocation setArgument:&relaunch atIndex:2];
|
||||
[invocation setTarget:self];
|
||||
postponedOnce = YES;
|
||||
if ([[updater delegate] updater:updater shouldPostponeRelaunchForUpdate:updateItem untilInvoking:invocation])
|
||||
return;
|
||||
}
|
||||
|
||||
[self cleanUp]; // Clean up the download and extracted files.
|
||||
|
||||
if ([[updater delegate] respondsToSelector:@selector(updater:willInstallUpdate:)])
|
||||
[[updater delegate] updater:updater willInstallUpdate:updateItem];
|
||||
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
|
||||
if ([delegate respondsToSelector:@selector(updaterWillRelaunchApplication)])
|
||||
[delegate updaterWillRelaunchApplication];
|
||||
// Copy the relauncher into a temporary directory so we can get to it after the new version's installed.
|
||||
NSString *relaunchPathToCopy = [SPARKLE_BUNDLE pathForResource:@"finish_installation" ofType:@"app"];
|
||||
NSString *targetPath = [[host appSupportPath] stringByAppendingPathComponent:[relaunchPathToCopy lastPathComponent]];
|
||||
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
|
||||
NSError *error = nil;
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
|
||||
[[NSFileManager defaultManager] createDirectoryAtPath: [targetPath stringByDeletingLastPathComponent] attributes: [NSDictionary dictionary]];
|
||||
#else
|
||||
[[NSFileManager defaultManager] createDirectoryAtPath: [targetPath stringByDeletingLastPathComponent] withIntermediateDirectories: YES attributes: [NSDictionary dictionary] error: &error];
|
||||
#endif
|
||||
|
||||
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
|
||||
if( [SUUpdater shouldUseXPCInstaller] )
|
||||
{
|
||||
[SUXPCInstaller copyPathWithAuthentication:relaunchPathToCopy overPath:targetPath temporaryName:nil completionHandler:^(NSError *xpcError) {
|
||||
if (xpcError != nil)
|
||||
NSLog(@"Error during asynchronous XPC call to copyPath: %@", xpcError);
|
||||
[self finishRelaunchAfterSuccessfulCopying:(xpcError == nil) fromPath:relaunchPathToCopy toPath:targetPath relaunch:relaunch];
|
||||
}];
|
||||
}
|
||||
else
|
||||
{
|
||||
BOOL copiedRelaunchTool = [SUPlainInstaller copyPathWithAuthentication: relaunchPathToCopy overPath: targetPath temporaryName: nil error: &error];
|
||||
[self finishRelaunchAfterSuccessfulCopying:copiedRelaunchTool fromPath:relaunchPathToCopy toPath:targetPath relaunch:relaunch];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)finishRelaunchAfterSuccessfulCopying:(BOOL)copiedRelaunchTool fromPath:(NSString *)relaunchPathToCopy toPath:(NSString *)targetPath relaunch:(BOOL)relaunch
|
||||
{
|
||||
|
||||
NSError *error = nil;
|
||||
if( copiedRelaunchTool )
|
||||
relaunchPath = [targetPath retain];
|
||||
else
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), NSLocalizedDescriptionKey, [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@", relaunchPathToCopy, targetPath, (error ? [error localizedDescription] : @"")], NSLocalizedFailureReasonErrorKey, nil]]];
|
||||
|
||||
if(!relaunchPath || ![[NSFileManager defaultManager] fileExistsAtPath:relaunchPath])
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self];
|
||||
if ([[updater delegate] respondsToSelector:@selector(updaterWillRelaunchApplication:)])
|
||||
[[updater delegate] updaterWillRelaunchApplication:updater];
|
||||
|
||||
if(!relaunchPath || ![[NSFileManager defaultManager] fileExistsAtPath:relaunchPath])
|
||||
{
|
||||
// Note that we explicitly use the host app's name here, since updating plugin for Mail relaunches Mail, not just the plugin.
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [host name]], NSLocalizedDescriptionKey, [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@)", relaunchPath], NSLocalizedFailureReasonErrorKey, nil]]];
|
||||
// We intentionally don't abandon the update here so that the host won't initiate another.
|
||||
return;
|
||||
}
|
||||
|
||||
NSString *pathToRelaunch = [host bundlePath];
|
||||
if ([[updater delegate] respondsToSelector:@selector(pathToRelaunchForUpdater:)])
|
||||
pathToRelaunch = [[updater delegate] pathToRelaunchForUpdater:updater];
|
||||
NSString *relaunchToolPath = [relaunchPath stringByAppendingPathComponent: @"/Contents/MacOS/finish_installation"];
|
||||
NSArray *arguments = [NSArray arrayWithObjects:[host bundlePath], pathToRelaunch, [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], tempDir, relaunch ? @"1" : @"0", nil];
|
||||
if( [SUUpdater shouldUseXPCInstaller] )
|
||||
[SUXPCInstaller launchTaskWithLaunchPath: relaunchToolPath arguments:arguments completionHandler:^{
|
||||
[NSApp terminate:self];
|
||||
}];
|
||||
else
|
||||
{
|
||||
[NSTask launchedTaskWithLaunchPath: relaunchToolPath arguments:arguments];
|
||||
[NSApp terminate:self];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)cleanUpDownload
|
||||
{
|
||||
if (tempDir != nil) // tempDir contains downloadPath, so we implicitly delete both here.
|
||||
{
|
||||
// Note that we explicitly use the host app's name here, since updating plugin for Mail relaunches Mail, not just the plugin.
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURelaunchError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [[NSBundle mainBundle] name]], NSLocalizedDescriptionKey, [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@)", relaunchPath], NSLocalizedFailureReasonErrorKey, nil]]];
|
||||
// We intentionally don't abandon the update here so that the host won't initiate another.
|
||||
return;
|
||||
}
|
||||
|
||||
[NSTask launchedTaskWithLaunchPath:relaunchPath arguments:[NSArray arrayWithObjects:[hostBundle bundlePath], [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], nil]];
|
||||
|
||||
[NSApp terminate:self];
|
||||
BOOL success = NO;
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
|
||||
success = [[NSFileManager defaultManager] removeFileAtPath: tempDir handler: nil]; // Clean up the copied relauncher
|
||||
#else
|
||||
NSError * error = nil;
|
||||
success = [[NSFileManager defaultManager] removeItemAtPath: tempDir error: &error]; // Clean up the copied relauncher
|
||||
#endif
|
||||
if( !success )
|
||||
[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[tempDir stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[tempDir lastPathComponent]] tag:NULL];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)cleanUp
|
||||
- (void)installerForHost:(SUHost *)aHost failedWithError:(NSError *)error
|
||||
{
|
||||
[[NSFileManager defaultManager] removeFileAtPath:[downloadPath stringByDeletingLastPathComponent] handler:nil];
|
||||
}
|
||||
|
||||
- (void)installerForHostBundle:(NSBundle *)hb failedWithError:(NSError *)error
|
||||
{
|
||||
if (hb != hostBundle) { return; }
|
||||
[[NSFileManager defaultManager] removeFileAtPath:relaunchPath handler:NULL]; // Clean up the copied relauncher.
|
||||
if (aHost != host) { return; }
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
|
||||
[[NSFileManager defaultManager] removeFileAtPath: relaunchPath handler: nil]; // Clean up the copied relauncher
|
||||
#else
|
||||
NSError * dontThrow = nil;
|
||||
[[NSFileManager defaultManager] removeItemAtPath: relaunchPath error: &dontThrow]; // Clean up the copied relauncher
|
||||
#endif
|
||||
[self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:SULocalizedString(@"An error occurred while installing the update. Please try again later.", nil), NSLocalizedDescriptionKey, [error localizedDescription], NSLocalizedFailureReasonErrorKey, nil]]];
|
||||
}
|
||||
|
||||
- (void)abortUpdate
|
||||
{
|
||||
[[self retain] autorelease]; // In case the notification center was the last one holding on to us.
|
||||
[self cleanUpDownload];
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
||||
[super abortUpdate];
|
||||
}
|
||||
@@ -265,16 +478,21 @@
|
||||
- (void)abortUpdateWithError:(NSError *)error
|
||||
{
|
||||
if ([error code] != SUNoUpdateError) // Let's not bother logging this.
|
||||
NSLog(@"Sparkle Error: %@", [error localizedDescription]);
|
||||
SULog(@"Sparkle Error: %@", [error localizedDescription]);
|
||||
if ([error localizedFailureReason])
|
||||
NSLog(@"Sparkle Error (continued): %@", [error localizedFailureReason]);
|
||||
SULog(@"Sparkle Error (continued): %@", [error localizedFailureReason]);
|
||||
if (download)
|
||||
[download cancel];
|
||||
[self abortUpdate];
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[hostBundle release];
|
||||
[updateItem release];
|
||||
[nonDeltaUpdateItem release];
|
||||
[download release];
|
||||
[downloadPath release];
|
||||
[tempDir release];
|
||||
[relaunchPath release];
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
//
|
||||
// SUBinaryDeltaApply.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mark Rowe on 2009-06-01.
|
||||
// Copyright 2009 Mark Rowe. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SUBINARYDELTAAPPLY_H
|
||||
#define SUBINARYDELTAAPPLY_H
|
||||
|
||||
@class NSString;
|
||||
int applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,101 @@
|
||||
//
|
||||
// SUBinaryDeltaApply.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mark Rowe on 2009-06-01.
|
||||
// Copyright 2009 Mark Rowe. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUBinaryDeltaApply.h"
|
||||
#import "SUBinaryDeltaCommon.h"
|
||||
#import <CommonCrypto/CommonDigest.h>
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <bspatch.h>
|
||||
#import <stdio.h>
|
||||
#import <stdlib.h>
|
||||
#import <xar/xar.h>
|
||||
|
||||
static void applyBinaryDeltaToFile(xar_t x, xar_file_t file, NSString *sourceFilePath, NSString *destinationFilePath)
|
||||
{
|
||||
NSString *patchFile = temporaryFilename(@"apply-binary-delta");
|
||||
xar_extract_tofile(x, file, [patchFile fileSystemRepresentation]);
|
||||
const char *argv[] = {"/usr/bin/bspatch", [sourceFilePath fileSystemRepresentation], [destinationFilePath fileSystemRepresentation], [patchFile fileSystemRepresentation]};
|
||||
bspatch(4, (char **)argv);
|
||||
unlink([patchFile fileSystemRepresentation]);
|
||||
}
|
||||
|
||||
int applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile)
|
||||
{
|
||||
xar_t x = xar_open([patchFile UTF8String], READ);
|
||||
if (!x) {
|
||||
fprintf(stderr, "Unable to open %s. Giving up.\n", [patchFile UTF8String]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
NSString *expectedBeforeHash = nil;
|
||||
NSString *expectedAfterHash = nil;
|
||||
xar_subdoc_t subdoc;
|
||||
for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) {
|
||||
if (!strcmp(xar_subdoc_name(subdoc), "binary-delta-attributes")) {
|
||||
const char *value = 0;
|
||||
xar_subdoc_prop_get(subdoc, "before-sha1", &value);
|
||||
if (value)
|
||||
expectedBeforeHash = [NSString stringWithUTF8String:value];
|
||||
|
||||
xar_subdoc_prop_get(subdoc, "after-sha1", &value);
|
||||
if (value)
|
||||
expectedAfterHash = [NSString stringWithUTF8String:value];
|
||||
}
|
||||
}
|
||||
|
||||
if (!expectedBeforeHash || !expectedAfterHash) {
|
||||
fprintf(stderr, "Unable to find before-sha1 or after-sha1 metadata in delta. Giving up.\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
fprintf(stderr, "Verifying source... ");
|
||||
NSString *beforeHash = hashOfTree(source);
|
||||
|
||||
if (![beforeHash isEqualToString:expectedBeforeHash]) {
|
||||
fprintf(stderr, "Source doesn't have expected hash (%s != %s). Giving up.\n", [expectedBeforeHash UTF8String], [beforeHash UTF8String]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
fprintf(stderr, "\nCopying files... ");
|
||||
removeTree(destination);
|
||||
copyTree(source, destination);
|
||||
|
||||
fprintf(stderr, "\nPatching... ");
|
||||
xar_file_t file;
|
||||
xar_iter_t iter = xar_iter_new();
|
||||
for (file = xar_file_first(x, iter); file; file = xar_file_next(iter)) {
|
||||
NSString *path = [NSString stringWithUTF8String:xar_get_path(file)];
|
||||
NSString *sourceFilePath = [source stringByAppendingPathComponent:path];
|
||||
NSString *destinationFilePath = [destination stringByAppendingPathComponent:path];
|
||||
|
||||
const char *value;
|
||||
if (!xar_prop_get(file, "delete", &value) || !xar_prop_get(file, "delete-then-extract", &value)) {
|
||||
removeTree(destinationFilePath);
|
||||
if (!xar_prop_get(file, "delete", &value))
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!xar_prop_get(file, "binary-delta", &value))
|
||||
applyBinaryDeltaToFile(x, file, sourceFilePath, destinationFilePath);
|
||||
else
|
||||
xar_extract_tofile(x, file, [destinationFilePath fileSystemRepresentation]);
|
||||
}
|
||||
xar_close(x);
|
||||
|
||||
fprintf(stderr, "\nVerifying destination... ");
|
||||
NSString *afterHash = hashOfTree(destination);
|
||||
|
||||
if (![afterHash isEqualToString:expectedAfterHash]) {
|
||||
fprintf(stderr, "Destination doesn't have expected hash (%s != %s). Giving up.\n", [expectedAfterHash UTF8String], [afterHash UTF8String]);
|
||||
removeTree(destination);
|
||||
return 1;
|
||||
}
|
||||
|
||||
fprintf(stderr, "\nDone!\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//
|
||||
// SUBinaryDeltaCommon.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mark Rowe on 2009-06-01.
|
||||
// Copyright 2009 Mark Rowe. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SUBINARYDELTACOMMON_H
|
||||
#define SUBINARYDELTACOMMON_H
|
||||
|
||||
#include <fts.h>
|
||||
|
||||
@class NSString;
|
||||
@class NSData;
|
||||
|
||||
extern int binaryDeltaSupported(void);
|
||||
extern int compareFiles(const FTSENT **a, const FTSENT **b);
|
||||
extern NSData *hashOfFile(FTSENT *ent);
|
||||
extern NSString *hashOfTree(NSString *path);
|
||||
extern void removeTree(NSString *path);
|
||||
extern void copyTree(NSString *source, NSString *dest);
|
||||
extern NSString *pathRelativeToDirectory(NSString *directory, NSString *path);
|
||||
NSString *temporaryFilename(NSString *base);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,165 @@
|
||||
//
|
||||
// SUBinaryDeltaCommon.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mark Rowe on 2009-06-01.
|
||||
// Copyright 2009 Mark Rowe. All rights reserved.
|
||||
//
|
||||
|
||||
#include "SUBinaryDeltaCommon.h"
|
||||
#include <CommonCrypto/CommonDigest.h>
|
||||
#include <Foundation/Foundation.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/param.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
extern int xar_close(void*) __attribute__((weak_import));
|
||||
|
||||
int binaryDeltaSupported(void)
|
||||
{
|
||||
// OS X 10.4 didn't include libxar, so we link against it weakly.
|
||||
// This checks whether libxar is available at runtime.
|
||||
return xar_close != 0;
|
||||
}
|
||||
|
||||
int compareFiles(const FTSENT **a, const FTSENT **b)
|
||||
{
|
||||
return strcoll((*a)->fts_name, (*b)->fts_name);
|
||||
}
|
||||
|
||||
NSString *pathRelativeToDirectory(NSString *directory, NSString *path)
|
||||
{
|
||||
NSUInteger directoryLength = [directory length];
|
||||
if ([path hasPrefix:directory])
|
||||
return [path substringFromIndex:directoryLength];
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
NSString *temporaryFilename(NSString *base)
|
||||
{
|
||||
NSString *template = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.XXXXXXXXXX", base]];
|
||||
char buffer[MAXPATHLEN];
|
||||
strcpy(buffer, [template fileSystemRepresentation]);
|
||||
return [NSString stringWithUTF8String:mktemp(buffer)];
|
||||
}
|
||||
|
||||
static void _hashOfBuffer(unsigned char *hash, const char* buffer, size_t bufferLength)
|
||||
{
|
||||
assert(bufferLength <= UINT32_MAX);
|
||||
CC_SHA1_CTX hashContext;
|
||||
CC_SHA1_Init(&hashContext);
|
||||
CC_SHA1_Update(&hashContext, buffer, (CC_LONG)bufferLength);
|
||||
CC_SHA1_Final(hash, &hashContext);
|
||||
}
|
||||
|
||||
static void _hashOfFile(unsigned char* hash, FTSENT *ent)
|
||||
{
|
||||
if (ent->fts_info == FTS_SL) {
|
||||
char linkDestination[MAXPATHLEN + 1];
|
||||
ssize_t linkDestinationLength = readlink(ent->fts_path, linkDestination, MAXPATHLEN);
|
||||
if (linkDestinationLength < 0) {
|
||||
perror("readlink");
|
||||
return;
|
||||
}
|
||||
|
||||
_hashOfBuffer(hash, linkDestination, linkDestinationLength);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ent->fts_info == FTS_F) {
|
||||
int fileDescriptor = open(ent->fts_path, O_RDONLY);
|
||||
if (fileDescriptor == -1) {
|
||||
perror("open");
|
||||
return;
|
||||
}
|
||||
|
||||
size_t fileSize = (size_t)ent->fts_statp->st_size;
|
||||
if (fileSize == 0) {
|
||||
_hashOfBuffer(hash, NULL, 0);
|
||||
close(fileDescriptor);
|
||||
return;
|
||||
}
|
||||
|
||||
void *buffer = mmap(0, fileSize, PROT_READ, MAP_FILE | MAP_PRIVATE, fileDescriptor, 0);
|
||||
if (buffer == (void*)-1) {
|
||||
close(fileDescriptor);
|
||||
perror("mmap");
|
||||
return;
|
||||
}
|
||||
|
||||
_hashOfBuffer(hash, buffer, fileSize);
|
||||
munmap(buffer, fileSize);
|
||||
close(fileDescriptor);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ent->fts_info == FTS_D)
|
||||
memset(hash, 0xdd, CC_SHA1_DIGEST_LENGTH);
|
||||
}
|
||||
|
||||
NSData *hashOfFile(FTSENT *ent)
|
||||
{
|
||||
unsigned char fileHash[CC_SHA1_DIGEST_LENGTH];
|
||||
_hashOfFile(fileHash, ent);
|
||||
return [NSData dataWithBytes:fileHash length:CC_SHA1_DIGEST_LENGTH];
|
||||
}
|
||||
|
||||
NSString *hashOfTree(NSString *path)
|
||||
{
|
||||
const char *sourcePaths[] = {[path UTF8String], 0};
|
||||
FTS *fts = fts_open((char* const*)sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
|
||||
if (!fts) {
|
||||
perror("fts_open");
|
||||
return nil;
|
||||
}
|
||||
|
||||
CC_SHA1_CTX hashContext;
|
||||
CC_SHA1_Init(&hashContext);
|
||||
|
||||
FTSENT *ent = 0;
|
||||
while ((ent = fts_read(fts))) {
|
||||
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL)
|
||||
continue;
|
||||
|
||||
unsigned char fileHash[CC_SHA1_DIGEST_LENGTH];
|
||||
_hashOfFile(fileHash, ent);
|
||||
CC_SHA1_Update(&hashContext, fileHash, sizeof(fileHash));
|
||||
|
||||
NSString *relativePath = pathRelativeToDirectory(path, [NSString stringWithUTF8String:ent->fts_path]);
|
||||
NSData *relativePathBytes = [relativePath dataUsingEncoding:NSUTF8StringEncoding];
|
||||
CC_SHA1_Update(&hashContext, [relativePathBytes bytes], (uint32_t)[relativePathBytes length]);
|
||||
}
|
||||
fts_close(fts);
|
||||
|
||||
unsigned char hash[CC_SHA1_DIGEST_LENGTH];
|
||||
CC_SHA1_Final(hash, &hashContext);
|
||||
|
||||
char hexHash[CC_SHA1_DIGEST_LENGTH * 2 + 1];
|
||||
size_t i;
|
||||
for (i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
|
||||
sprintf(hexHash + i * 2, "%02x", hash[i]);
|
||||
|
||||
return [NSString stringWithUTF8String:hexHash];
|
||||
}
|
||||
|
||||
void removeTree(NSString *path)
|
||||
{
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
|
||||
[[NSFileManager defaultManager] removeItemAtPath:path error:0];
|
||||
#else
|
||||
[[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
|
||||
#endif
|
||||
}
|
||||
|
||||
void copyTree(NSString *source, NSString *dest)
|
||||
{
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
|
||||
[[NSFileManager defaultManager] copyItemAtPath:source toPath:dest error:0];
|
||||
#else
|
||||
[[NSFileManager defaultManager] copyPath:source toPath:dest handler:nil];
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
//
|
||||
// SUBinaryDeltaTool.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mark Rowe on 2009-06-01.
|
||||
// Copyright 2009 Mark Rowe. All rights reserved.
|
||||
//
|
||||
|
||||
#define _DARWIN_NO_64_BIT_INODE 1
|
||||
|
||||
#include "SUBinaryDeltaCommon.h"
|
||||
#include "SUBinaryDeltaApply.h"
|
||||
#include <CommonCrypto/CommonDigest.h>
|
||||
#include <Foundation/Foundation.h>
|
||||
#include <fcntl.h>
|
||||
#include <fts.h>
|
||||
#include <libgen.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/param.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <xar/xar.h>
|
||||
|
||||
extern int bsdiff(int argc, const char **argv);
|
||||
|
||||
@interface CreateBinaryDeltaOperation : NSOperation
|
||||
{
|
||||
NSString *_relativePath;
|
||||
NSString *_fromPath;
|
||||
NSString *_toPath;
|
||||
NSString *_resultPath;
|
||||
}
|
||||
- (id)initWithRelativePath:(NSString *)relativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree;
|
||||
|
||||
- (NSString *)relativePath;
|
||||
- (NSString *)resultPath;
|
||||
@end
|
||||
|
||||
@implementation CreateBinaryDeltaOperation
|
||||
|
||||
- (id)initWithRelativePath:(NSString *)relativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree
|
||||
{
|
||||
if ((self = [super init])) {
|
||||
_relativePath = [relativePath copy];
|
||||
_fromPath = [[oldTree stringByAppendingPathComponent:relativePath] retain];
|
||||
_toPath = [[newTree stringByAppendingPathComponent:relativePath] retain];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (NSString *)relativePath
|
||||
{
|
||||
return [[_relativePath retain] autorelease];
|
||||
}
|
||||
|
||||
- (NSString *)resultPath
|
||||
{
|
||||
return [[_resultPath retain] autorelease];
|
||||
}
|
||||
|
||||
- (void)main
|
||||
{
|
||||
NSString *temporaryFile = temporaryFilename(@"BinaryDelta");
|
||||
const char *argv[] = {"/usr/bin/bsdiff", [_fromPath fileSystemRepresentation], [_toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation]};
|
||||
int result = bsdiff(4, argv);
|
||||
if (!result)
|
||||
_resultPath = [temporaryFile retain];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
static NSDictionary *infoForFile(FTSENT *ent)
|
||||
{
|
||||
NSData *hash = hashOfFile(ent);
|
||||
NSNumber *size = nil;
|
||||
if (ent->fts_info != FTS_D)
|
||||
size = [NSNumber numberWithUnsignedLongLong:ent->fts_statp->st_size];
|
||||
return [NSDictionary dictionaryWithObjectsAndKeys:hash, @"hash", [NSNumber numberWithUnsignedShort:ent->fts_info], @"type", size, @"size", nil];
|
||||
}
|
||||
|
||||
static NSString *absolutePath(NSString *path)
|
||||
{
|
||||
NSURL *url = [[[NSURL alloc] initFileURLWithPath:path] autorelease];
|
||||
return [[url absoluteURL] path];
|
||||
}
|
||||
|
||||
static NSString *temporaryPatchFile(NSString *patchFile)
|
||||
{
|
||||
NSString *path = absolutePath(patchFile);
|
||||
NSString *directory = [path stringByDeletingLastPathComponent];
|
||||
NSString *file = [path lastPathComponent];
|
||||
return [NSString stringWithFormat:@"%@/.%@.tmp", directory, file];
|
||||
}
|
||||
|
||||
static BOOL shouldSkipDeltaCompression(NSString *key, NSDictionary* originalInfo, NSDictionary *newInfo)
|
||||
{
|
||||
unsigned long long fileSize = [[newInfo objectForKey:@"size"] unsignedLongLongValue];
|
||||
if (fileSize < 4096)
|
||||
return YES;
|
||||
|
||||
if (!originalInfo)
|
||||
return YES;
|
||||
|
||||
if ([[originalInfo objectForKey:@"type"] unsignedShortValue] != [[newInfo objectForKey:@"type"] unsignedShortValue])
|
||||
return YES;
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
static BOOL shouldDeleteThenExtract(NSString *key, NSDictionary* originalInfo, NSDictionary *newInfo)
|
||||
{
|
||||
if (!originalInfo)
|
||||
return NO;
|
||||
|
||||
if ([[originalInfo objectForKey:@"type"] unsignedShortValue] != [[newInfo objectForKey:@"type"] unsignedShortValue])
|
||||
return YES;
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc != 5) {
|
||||
usage:
|
||||
fprintf(stderr, "Usage: BinaryDelta [create | apply] before-tree after-tree patch-file\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
|
||||
|
||||
NSString *command = [NSString stringWithUTF8String:argv[1]];
|
||||
NSString *oldPath = [NSString stringWithUTF8String:argv[2]];
|
||||
NSString *newPath = [NSString stringWithUTF8String:argv[3]];
|
||||
NSString *patchFile = [NSString stringWithUTF8String:argv[4]];
|
||||
|
||||
if ([command isEqualToString:@"apply"]) {
|
||||
int result = applyBinaryDelta(oldPath, newPath, patchFile);
|
||||
[pool drain];
|
||||
return result;
|
||||
}
|
||||
if (![command isEqualToString:@"create"]) {
|
||||
[pool drain];
|
||||
goto usage;
|
||||
}
|
||||
|
||||
NSMutableDictionary *originalTreeState = [NSMutableDictionary dictionary];
|
||||
|
||||
const char *sourcePaths[] = {[oldPath fileSystemRepresentation], 0};
|
||||
FTS *fts = fts_open((char* const*)sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
|
||||
if (!fts) {
|
||||
[pool drain];
|
||||
perror("fts_open");
|
||||
return 1;
|
||||
}
|
||||
|
||||
fprintf(stderr, "Processing %s...", [oldPath UTF8String]);
|
||||
FTSENT *ent = 0;
|
||||
while ((ent = fts_read(fts))) {
|
||||
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D)
|
||||
continue;
|
||||
|
||||
NSString *key = pathRelativeToDirectory(oldPath, [NSString stringWithUTF8String:ent->fts_path]);
|
||||
if (![key length])
|
||||
continue;
|
||||
|
||||
NSDictionary *info = infoForFile(ent);
|
||||
[originalTreeState setObject:info forKey:key];
|
||||
}
|
||||
fts_close(fts);
|
||||
|
||||
NSString *beforeHash = hashOfTree(oldPath);
|
||||
|
||||
NSMutableDictionary *newTreeState = [NSMutableDictionary dictionary];
|
||||
for (NSString *key in originalTreeState)
|
||||
{
|
||||
[newTreeState setObject:[NSNull null] forKey:key];
|
||||
}
|
||||
|
||||
fprintf(stderr, "\nProcessing %s... ", [newPath UTF8String]);
|
||||
sourcePaths[0] = [newPath fileSystemRepresentation];
|
||||
fts = fts_open((char* const*)sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles);
|
||||
if (!fts) {
|
||||
[pool drain];
|
||||
perror("fts_open");
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
while ((ent = fts_read(fts))) {
|
||||
if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D)
|
||||
continue;
|
||||
|
||||
NSString *key = pathRelativeToDirectory(newPath, [NSString stringWithUTF8String:ent->fts_path]);
|
||||
if (![key length])
|
||||
continue;
|
||||
|
||||
NSDictionary *info = infoForFile(ent);
|
||||
NSDictionary *oldInfo = [originalTreeState objectForKey:key];
|
||||
|
||||
if ([info isEqual:oldInfo])
|
||||
[newTreeState removeObjectForKey:key];
|
||||
else
|
||||
[newTreeState setObject:info forKey:key];
|
||||
}
|
||||
fts_close(fts);
|
||||
|
||||
NSString *afterHash = hashOfTree(newPath);
|
||||
|
||||
fprintf(stderr, "\nGenerating delta... ");
|
||||
|
||||
NSString *temporaryFile = temporaryPatchFile(patchFile);
|
||||
xar_t x = xar_open([temporaryFile fileSystemRepresentation], WRITE);
|
||||
xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2");
|
||||
xar_subdoc_t attributes = xar_subdoc_new(x, "binary-delta-attributes");
|
||||
xar_subdoc_prop_set(attributes, "before-sha1", [beforeHash UTF8String]);
|
||||
xar_subdoc_prop_set(attributes, "after-sha1", [afterHash UTF8String]);
|
||||
|
||||
NSOperationQueue *deltaQueue = [[NSOperationQueue alloc] init];
|
||||
NSMutableArray *deltaOperations = [NSMutableArray array];
|
||||
|
||||
NSArray *keys = [[newTreeState allKeys] sortedArrayUsingSelector:@selector(compare:)];
|
||||
for (NSString* key in keys) {
|
||||
id value = [newTreeState valueForKey:key];
|
||||
|
||||
if ([value isEqual:[NSNull null]]) {
|
||||
xar_file_t newFile = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1);
|
||||
assert(newFile);
|
||||
xar_prop_set(newFile, "delete", "true");
|
||||
continue;
|
||||
}
|
||||
|
||||
NSDictionary *originalInfo = [originalTreeState objectForKey:key];
|
||||
NSDictionary *newInfo = [newTreeState objectForKey:key];
|
||||
if (shouldSkipDeltaCompression(key, originalInfo, newInfo)) {
|
||||
NSString *path = [newPath stringByAppendingPathComponent:key];
|
||||
xar_file_t newFile = xar_add_frompath(x, 0, [key fileSystemRepresentation], [path fileSystemRepresentation]);
|
||||
assert(newFile);
|
||||
if (shouldDeleteThenExtract(key, originalInfo, newInfo))
|
||||
xar_prop_set(newFile, "delete-then-extract", "true");
|
||||
} else {
|
||||
CreateBinaryDeltaOperation *operation = [[CreateBinaryDeltaOperation alloc] initWithRelativePath:key oldTree:oldPath newTree:newPath];
|
||||
[deltaQueue addOperation:operation];
|
||||
[deltaOperations addObject:operation];
|
||||
[operation release];
|
||||
}
|
||||
}
|
||||
|
||||
[deltaQueue waitUntilAllOperationsAreFinished];
|
||||
[deltaQueue release];
|
||||
|
||||
for (CreateBinaryDeltaOperation *operation in deltaOperations) {
|
||||
NSString *resultPath = [operation resultPath];
|
||||
xar_file_t newFile = xar_add_frompath(x, 0, [[operation relativePath] fileSystemRepresentation], [resultPath fileSystemRepresentation]);
|
||||
assert(newFile);
|
||||
xar_prop_set(newFile, "binary-delta", "true");
|
||||
unlink([resultPath fileSystemRepresentation]);
|
||||
}
|
||||
|
||||
xar_close(x);
|
||||
|
||||
unlink([patchFile fileSystemRepresentation]);
|
||||
link([temporaryFile fileSystemRepresentation], [patchFile fileSystemRepresentation]);
|
||||
unlink([temporaryFile fileSystemRepresentation]);
|
||||
fprintf(stderr, "Done!\n");
|
||||
|
||||
[pool drain];
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// SUBinaryDeltaUnarchiver.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mark Rowe on 2009-06-03.
|
||||
// Copyright 2009 Mark Rowe. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SUBINARYDELTAUNARCHIVER_H
|
||||
#define SUBINARYDELTAUNARCHIVER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUUnarchiver.h"
|
||||
|
||||
@interface SUBinaryDeltaUnarchiver : SUUnarchiver {
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,48 @@
|
||||
//
|
||||
// SUBinaryDeltaUnarchiver.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mark Rowe on 2009-06-03.
|
||||
// Copyright 2009 Mark Rowe. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUBinaryDeltaCommon.h"
|
||||
#import "SUBinaryDeltaUnarchiver.h"
|
||||
#import "SUBinaryDeltaApply.h"
|
||||
#import "SUUnarchiver_Private.h"
|
||||
#import "SUHost.h"
|
||||
#import "NTSynchronousTask.h"
|
||||
|
||||
@implementation SUBinaryDeltaUnarchiver
|
||||
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path
|
||||
{
|
||||
return binaryDeltaSupported() && [[path pathExtension] isEqualToString:@"delta"];
|
||||
}
|
||||
|
||||
- (void)applyBinaryDelta
|
||||
{
|
||||
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
|
||||
NSString *sourcePath = [[updateHost bundle] bundlePath];
|
||||
NSString *targetPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]];
|
||||
|
||||
int result = applyBinaryDelta(sourcePath, targetPath, archivePath);
|
||||
if (!result)
|
||||
[self performSelectorOnMainThread:@selector(notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO];
|
||||
else
|
||||
[self performSelectorOnMainThread:@selector(notifyDelegateOfFailure) withObject:nil waitUntilDone:NO];
|
||||
|
||||
[pool drain];
|
||||
}
|
||||
|
||||
- (void)start
|
||||
{
|
||||
[NSThread detachNewThreadSelector:@selector(applyBinaryDelta) toTarget:self withObject:nil];
|
||||
}
|
||||
|
||||
+ (void)load
|
||||
{
|
||||
[self registerImplementation:self];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,24 @@
|
||||
//
|
||||
// SUCodeSigningVerifier.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 7/5/12.
|
||||
//
|
||||
//
|
||||
|
||||
#ifndef SUCODESIGNINGVERIFIER_H
|
||||
#define SUCODESIGNINGVERIFIER_H
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface SUCodeSigningVerifier : NSObject
|
||||
|
||||
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)destinationPath error:(NSError **)error;
|
||||
|
||||
+ (BOOL)hostApplicationIsCodeSigned;
|
||||
+ (BOOL)hostApplicationIsSandboxed;
|
||||
+ (BOOL)hostAppAllowsNetworkOutgoingConnections;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,191 @@
|
||||
//
|
||||
// SUCodeSigningVerifier.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 7/5/12.
|
||||
//
|
||||
//
|
||||
|
||||
#import <Security/CodeSigning.h>
|
||||
#import "SUCodeSigningVerifier.h"
|
||||
#import "SULog.h"
|
||||
|
||||
@implementation SUCodeSigningVerifier
|
||||
|
||||
extern OSStatus SecCodeCopySelf(SecCSFlags flags, SecCodeRef *self) __attribute__((weak_import));
|
||||
extern OSStatus SecCodeCopyDesignatedRequirement(SecStaticCodeRef code, SecCSFlags flags, SecRequirementRef *requirement) __attribute__((weak_import));
|
||||
extern OSStatus SecStaticCodeCreateWithPath(CFURLRef path, SecCSFlags flags, SecStaticCodeRef *staticCode) __attribute__((weak_import));
|
||||
extern OSStatus SecStaticCodeCheckValidityWithErrors(SecStaticCodeRef staticCode, SecCSFlags flags, SecRequirementRef requirement, CFErrorRef *errors) __attribute__((weak_import));
|
||||
extern OSStatus SecRequirementCreateWithString(CFStringRef text, SecCSFlags flags, SecRequirementRef *requirement) __attribute__((weak_import));
|
||||
extern OSStatus SecCodeCheckValidity(SecCodeRef code, SecCSFlags flags, SecRequirementRef requirement) __attribute__((weak_import));
|
||||
|
||||
+ (BOOL)codeSignatureIsValidAtPath:(NSString *)destinationPath error:(NSError **)error
|
||||
{
|
||||
// This API didn't exist prior to 10.6.
|
||||
if (SecCodeCopySelf == NULL) return NO;
|
||||
|
||||
OSStatus result;
|
||||
SecRequirementRef requirement = NULL;
|
||||
SecStaticCodeRef staticCode = NULL;
|
||||
SecCodeRef hostCode = NULL;
|
||||
|
||||
result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
|
||||
if (result != 0) {
|
||||
SULog(@"Failed to copy host code %d", result);
|
||||
goto finally;
|
||||
}
|
||||
|
||||
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
|
||||
if (result != 0) {
|
||||
SULog(@"Failed to copy designated requirement %d", result);
|
||||
goto finally;
|
||||
}
|
||||
|
||||
NSBundle *newBundle = [NSBundle bundleWithPath:destinationPath];
|
||||
if (!newBundle) {
|
||||
SULog(@"Failed to load NSBundle for update");
|
||||
result = -1;
|
||||
goto finally;
|
||||
}
|
||||
|
||||
result = SecStaticCodeCreateWithPath((CFURLRef)[newBundle executableURL], kSecCSDefaultFlags, &staticCode);
|
||||
if (result != 0) {
|
||||
SULog(@"Failed to get static code %d", result);
|
||||
goto finally;
|
||||
}
|
||||
|
||||
result = SecStaticCodeCheckValidityWithErrors(staticCode, kSecCSDefaultFlags | kSecCSCheckAllArchitectures, requirement, (CFErrorRef *)error);
|
||||
if (result != 0 && error) [*error autorelease];
|
||||
|
||||
finally:
|
||||
if (hostCode) CFRelease(hostCode);
|
||||
if (staticCode) CFRelease(staticCode);
|
||||
if (requirement) CFRelease(requirement);
|
||||
return (result == 0);
|
||||
}
|
||||
|
||||
+ (BOOL)hostApplicationIsCodeSigned
|
||||
{
|
||||
static BOOL sIsCodesigned = NO;
|
||||
|
||||
static BOOL onceToken = NO;
|
||||
while (!onceToken)
|
||||
{
|
||||
onceToken = YES;
|
||||
|
||||
// This API didn't exist prior to 10.6.
|
||||
if (SecCodeCopySelf == NULL)
|
||||
break;
|
||||
|
||||
SecCodeRef hostCode = NULL;
|
||||
OSStatus result = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
|
||||
if (result != noErr)
|
||||
break;
|
||||
|
||||
SecRequirementRef requirement = NULL;
|
||||
result = SecCodeCopyDesignatedRequirement(hostCode, kSecCSDefaultFlags, &requirement);
|
||||
|
||||
if (hostCode) CFRelease(hostCode);
|
||||
if (requirement) CFRelease(requirement);
|
||||
|
||||
sIsCodesigned = (noErr == result);
|
||||
}
|
||||
|
||||
return sIsCodesigned;
|
||||
}
|
||||
|
||||
+ (BOOL)hostApplicationIsSandboxed
|
||||
{
|
||||
static BOOL sIsAppSandboxed = NO;
|
||||
|
||||
static BOOL onceToken = NO;
|
||||
while (!onceToken)
|
||||
{
|
||||
onceToken = YES;
|
||||
|
||||
// This API didn't exist prior to 10.6
|
||||
if (SecCodeCopySelf == NULL)
|
||||
break;
|
||||
|
||||
SecCodeRef hostCode = NULL;
|
||||
SecRequirementRef hostRequirement = NULL;
|
||||
|
||||
#define Cleanup() \
|
||||
{ \
|
||||
if (hostCode) CFRelease(hostCode); \
|
||||
if (hostRequirement) CFRelease(hostRequirement); \
|
||||
}
|
||||
|
||||
OSStatus status = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
|
||||
|
||||
if (status != noErr || hostCode == NULL)
|
||||
{
|
||||
Cleanup();
|
||||
break;
|
||||
}
|
||||
|
||||
CFStringRef requirementString = CFSTR("entitlement[\"com.apple.security.app-sandbox\"] exists");
|
||||
status = SecRequirementCreateWithString(requirementString, kSecCSDefaultFlags, &hostRequirement);
|
||||
|
||||
if (status != noErr || hostRequirement == NULL)
|
||||
{
|
||||
Cleanup();
|
||||
break;
|
||||
}
|
||||
|
||||
status = SecCodeCheckValidity(hostCode, kSecCSDefaultFlags, hostRequirement);
|
||||
sIsAppSandboxed = (noErr == status);
|
||||
Cleanup();
|
||||
}
|
||||
|
||||
return sIsAppSandboxed;
|
||||
}
|
||||
|
||||
+ (BOOL)hostAppAllowsNetworkOutgoingConnections
|
||||
{
|
||||
static BOOL sIsAppAllowsOutgoingConnections = NO;
|
||||
|
||||
static BOOL onceToken = NO;
|
||||
while (!onceToken)
|
||||
{
|
||||
onceToken = YES;
|
||||
|
||||
if (![self hostApplicationIsSandboxed])
|
||||
{
|
||||
sIsAppAllowsOutgoingConnections = YES;
|
||||
break;
|
||||
}
|
||||
|
||||
SecCodeRef hostCode = NULL;
|
||||
SecRequirementRef hostRequirement = NULL;
|
||||
|
||||
#define Cleanup() \
|
||||
{ \
|
||||
if (hostCode) CFRelease(hostCode); \
|
||||
if (hostRequirement) CFRelease(hostRequirement); \
|
||||
}
|
||||
|
||||
OSStatus status = SecCodeCopySelf(kSecCSDefaultFlags, &hostCode);
|
||||
if (status != noErr || hostCode == NULL)
|
||||
{
|
||||
Cleanup();
|
||||
break;
|
||||
}
|
||||
|
||||
CFStringRef requirementString = CFSTR("entitlement[\"com.apple.security.network.client\"] exists");
|
||||
status = SecRequirementCreateWithString(requirementString, kSecCSDefaultFlags, &hostRequirement);
|
||||
if (status != noErr || hostRequirement == NULL)
|
||||
{
|
||||
Cleanup();
|
||||
break;
|
||||
}
|
||||
|
||||
status = SecCodeCheckValidity(hostCode, kSecCSDefaultFlags, hostRequirement);
|
||||
sIsAppAllowsOutgoingConnections = (noErr == status);
|
||||
Cleanup();
|
||||
}
|
||||
|
||||
return sIsAppAllowsOutgoingConnections;
|
||||
}
|
||||
|
||||
@end
|
||||
+62
-18
@@ -10,27 +10,64 @@
|
||||
#ifndef SUCONSTANTS_H
|
||||
#define SUCONSTANTS_H
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
extern NSString *SUUpdaterWillRestartNotification;
|
||||
extern NSString *SUTechnicalErrorInformationKey;
|
||||
// -----------------------------------------------------------------------------
|
||||
// Preprocessor flags:
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
extern NSString *SUFeedURLKey;
|
||||
extern NSString *SUHasLaunchedBeforeKey;
|
||||
extern NSString *SUShowReleaseNotesKey;
|
||||
extern NSString *SUSkippedVersionKey;
|
||||
extern NSString *SUScheduledCheckIntervalKey;
|
||||
extern NSString *SULastCheckTimeKey;
|
||||
extern NSString *SUExpectsDSASignatureKey;
|
||||
extern NSString *SUPublicDSAKeyKey;
|
||||
extern NSString *SUPublicDSAKeyFileKey;
|
||||
extern NSString *SUAutomaticallyUpdateKey;
|
||||
extern NSString *SUAllowsAutomaticUpdatesKey;
|
||||
extern NSString *SUEnableAutomaticChecksKey;
|
||||
extern NSString *SUEnableAutomaticChecksKeyOld;
|
||||
extern NSString *SUEnableSystemProfilingKey;
|
||||
extern NSString *SUSendProfileInfoKey;
|
||||
// Turn off DSA signature check (practically invites man-in-the-middle attacks):
|
||||
#define ENDANGER_USERS_WITH_INSECURE_UPDATES 0
|
||||
|
||||
extern NSString *SUSparkleErrorDomain;
|
||||
// Sparkle usually doesn't allow downgrades as they're usually accidental, but
|
||||
// if your app has a downgrade function or URL handler, turn this on:
|
||||
#define PERMIT_AUTOMATED_DOWNGRADES 0
|
||||
|
||||
// If your app file on disk is named "MyApp 1.1b4", Sparkle usually updates it
|
||||
// in place, giving you an app named 1.1b4 that is actually 1.2. Turn the
|
||||
// following on to always reset the name back to "MyApp":
|
||||
#define NORMALIZE_INSTALLED_APP_NAME 0
|
||||
|
||||
|
||||
#define TRY_TO_APPEND_VERSION_NUMBER 1
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Notifications:
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
extern NSString *const SUUpdaterWillRestartNotification;
|
||||
|
||||
extern NSString *const SUTechnicalErrorInformationKey;
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// PList keys::
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
extern NSString *const SUFeedURLKey;
|
||||
extern NSString *const SUHasLaunchedBeforeKey;
|
||||
extern NSString *const SUShowReleaseNotesKey;
|
||||
extern NSString *const SUSkippedVersionKey;
|
||||
extern NSString *const SUScheduledCheckIntervalKey;
|
||||
extern NSString *const SULastCheckTimeKey;
|
||||
extern NSString *const SUPublicDSAKeyKey;
|
||||
extern NSString *const SUPublicDSAKeyFileKey;
|
||||
extern NSString *const SUAutomaticallyUpdateKey;
|
||||
extern NSString *const SUAllowsAutomaticUpdatesKey;
|
||||
extern NSString *const SUEnableAutomaticChecksKey;
|
||||
extern NSString *const SUEnableAutomaticChecksKeyOld;
|
||||
extern NSString *const SUEnableSystemProfilingKey;
|
||||
extern NSString *const SUSendProfileInfoKey;
|
||||
extern NSString *const SULastProfileSubmitDateKey;
|
||||
extern NSString *const SUPromptUserOnFirstLaunchKey;
|
||||
extern NSString *const SUFixedHTMLDisplaySizeKey;
|
||||
extern NSString *const SUKeepDownloadOnFailedInstallKey;
|
||||
extern NSString *const SUDefaultsDomainKey;
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Errors:
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
extern NSString *const SUSparkleErrorDomain;
|
||||
// Appcast phase errors.
|
||||
extern OSStatus SUAppcastParseError;
|
||||
extern OSStatus SUNoUpdateError;
|
||||
@@ -51,6 +88,13 @@ extern OSStatus SUMissingUpdateError;
|
||||
extern OSStatus SUMissingInstallerToolError;
|
||||
extern OSStatus SURelaunchError;
|
||||
extern OSStatus SUInstallationError;
|
||||
extern OSStatus SUDowngradeError;
|
||||
extern OSStatus SUXPCServiceError;
|
||||
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// NSInteger fixer-upper:
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
// NSInteger is a type that was added to Leopard.
|
||||
// Here is some glue to ensure that NSInteger will work with pre-10.5 SDKs:
|
||||
|
||||
+25
-19
@@ -6,29 +6,33 @@
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "Sparkle.h"
|
||||
#import "SUConstants.h"
|
||||
|
||||
NSString *SUUpdaterWillRestartNotification = @"SUUpdaterWillRestartNotificationName";
|
||||
NSString *SUTechnicalErrorInformationKey = @"SUTechnicalErrorInformation";
|
||||
NSString *const SUUpdaterWillRestartNotification = @"SUUpdaterWillRestartNotificationName";
|
||||
NSString *const SUTechnicalErrorInformationKey = @"SUTechnicalErrorInformation";
|
||||
|
||||
NSString *SUHasLaunchedBeforeKey = @"SUHasLaunchedBefore";
|
||||
NSString *SUFeedURLKey = @"SUFeedURL";
|
||||
NSString *SUShowReleaseNotesKey = @"SUShowReleaseNotes";
|
||||
NSString *SUSkippedVersionKey = @"SUSkippedVersion";
|
||||
NSString *SUScheduledCheckIntervalKey = @"SUScheduledCheckInterval";
|
||||
NSString *SULastCheckTimeKey = @"SULastCheckTime";
|
||||
NSString *SUExpectsDSASignatureKey = @"SUExpectsDSASignature";
|
||||
NSString *SUPublicDSAKeyKey = @"SUPublicDSAKey";
|
||||
NSString *SUPublicDSAKeyFileKey = @"SUPublicDSAKeyFile";
|
||||
NSString *SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate";
|
||||
NSString *SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates";
|
||||
NSString *SUEnableSystemProfilingKey = @"SUEnableSystemProfiling";
|
||||
NSString *SUEnableAutomaticChecksKey = @"SUEnableAutomaticChecks";
|
||||
NSString *SUEnableAutomaticChecksKeyOld = @"SUCheckAtStartup";
|
||||
NSString *SUSendProfileInfoKey = @"SUSendProfileInfo";
|
||||
NSString *const SUHasLaunchedBeforeKey = @"SUHasLaunchedBefore";
|
||||
NSString *const SUFeedURLKey = @"SUFeedURL";
|
||||
NSString *const SUShowReleaseNotesKey = @"SUShowReleaseNotes";
|
||||
NSString *const SUSkippedVersionKey = @"SUSkippedVersion";
|
||||
NSString *const SUScheduledCheckIntervalKey = @"SUScheduledCheckInterval";
|
||||
NSString *const SULastCheckTimeKey = @"SULastCheckTime";
|
||||
NSString *const SUExpectsDSASignatureKey = @"SUExpectsDSASignature";
|
||||
NSString *const SUPublicDSAKeyKey = @"SUPublicDSAKey";
|
||||
NSString *const SUPublicDSAKeyFileKey = @"SUPublicDSAKeyFile";
|
||||
NSString *const SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate";
|
||||
NSString *const SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates";
|
||||
NSString *const SUEnableSystemProfilingKey = @"SUEnableSystemProfiling";
|
||||
NSString *const SUEnableAutomaticChecksKey = @"SUEnableAutomaticChecks";
|
||||
NSString *const SUEnableAutomaticChecksKeyOld = @"SUCheckAtStartup";
|
||||
NSString *const SUSendProfileInfoKey = @"SUSendProfileInfo";
|
||||
NSString *const SULastProfileSubmitDateKey = @"SULastProfileSubmissionDate";
|
||||
NSString *const SUPromptUserOnFirstLaunchKey = @"SUPromptUserOnFirstLaunch";
|
||||
NSString *const SUFixedHTMLDisplaySizeKey = @"SUFixedHTMLDisplaySize";
|
||||
NSString *const SUKeepDownloadOnFailedInstallKey = @"SUKeepDownloadOnFailedInstall";
|
||||
NSString *const SUDefaultsDomainKey = @"SUDefaultsDomain";
|
||||
|
||||
NSString *SUSparkleErrorDomain = @"SUSparkleErrorDomain";
|
||||
NSString *const SUSparkleErrorDomain = @"SUSparkleErrorDomain";
|
||||
OSStatus SUAppcastParseError = 1000;
|
||||
OSStatus SUNoUpdateError = 1001;
|
||||
OSStatus SUAppcastError = 1002;
|
||||
@@ -45,3 +49,5 @@ OSStatus SUMissingUpdateError = 4002;
|
||||
OSStatus SUMissingInstallerToolError = 4003;
|
||||
OSStatus SURelaunchError = 4004;
|
||||
OSStatus SUInstallationError = 4005;
|
||||
OSStatus SUDowngradeError = 4006;
|
||||
OSStatus SUXPCServiceError = 4007;
|
||||
@@ -0,0 +1,18 @@
|
||||
//
|
||||
// SUDSAVerifier.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 3/16/06.
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SUDSAVERIFIER_H
|
||||
#define SUDSAVERIFIER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@interface SUDSAVerifier : NSObject {}
|
||||
+ (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString;
|
||||
@end
|
||||
|
||||
#endif
|
||||
+357
@@ -0,0 +1,357 @@
|
||||
//
|
||||
// SUDSAVerifier.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Andy Matuschak on 3/16/06.
|
||||
// Copyright 2006 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUDSAVerifier.h"
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
#import <Security/cssm.h>
|
||||
|
||||
/* CDSA Specific */
|
||||
static CSSM_CSP_HANDLE cdsaInit( void );
|
||||
static void cdsaRelease( CSSM_CSP_HANDLE cspHandle );
|
||||
static CSSM_KEY_PTR cdsaCreateKey( CFDataRef rawKey );
|
||||
static void cdsaReleaseKey( CSSM_KEY_PTR key );
|
||||
static BOOL cdsaVerifyKey( CSSM_CSP_HANDLE cspHandle, const CSSM_KEY_PTR key );
|
||||
static BOOL cdsaVerifySignature( CSSM_CSP_HANDLE cspHandle, const CSSM_KEY_PTR key, const CFDataRef msg, const CFDataRef signature );
|
||||
static CFDataRef cdsaCreateSHA1Digest( CSSM_CSP_HANDLE cspHandle, const CFDataRef bytes );
|
||||
|
||||
/* Helper Functions */
|
||||
static NSData *b64decode( NSString *str );
|
||||
static NSData *rawKeyData( NSString *str );
|
||||
|
||||
@implementation SUDSAVerifier
|
||||
#pragma mark -
|
||||
|
||||
+ (BOOL)validatePath:(NSString *)path withEncodedDSASignature:(NSString *)encodedSignature withPublicDSAKey:(NSString *)pkeyString
|
||||
{
|
||||
if ( !encodedSignature || !pkeyString || !path ) return NO;
|
||||
BOOL result = NO;
|
||||
NSData *pathData = nil, *sigData = nil;
|
||||
CFDataRef hashData = NULL;
|
||||
CSSM_KEY_PTR pubKey = cdsaCreateKey((CFDataRef)rawKeyData(pkeyString)); // Create the DSA key
|
||||
CSSM_CSP_HANDLE cspHandle = CSSM_INVALID_HANDLE;
|
||||
|
||||
if ( !pubKey ) return NO;
|
||||
if ( (cspHandle = cdsaInit()) == CSSM_INVALID_HANDLE ) goto validate_end; // Init CDSA
|
||||
if ( !cdsaVerifyKey(cspHandle, pubKey) ) goto validate_end; // Verify the key is valid
|
||||
if ( (pathData = [NSData dataWithContentsOfFile:path]) == nil ) goto validate_end; // File data
|
||||
if ( (hashData = cdsaCreateSHA1Digest(cspHandle, (CFDataRef)pathData)) == NULL ) goto validate_end; // Hash
|
||||
|
||||
// Remove any line feeds from end of signature
|
||||
// (Not likely needed, but the verify _can_ fail if there is, so...)
|
||||
if ( [encodedSignature characterAtIndex:[encodedSignature length] - 1] == '\n' ) {
|
||||
NSMutableString *sig = [[encodedSignature mutableCopy] autorelease];
|
||||
while ( [sig characterAtIndex:[sig length] - 1] == '\n' )
|
||||
[sig deleteCharactersInRange:NSMakeRange([sig length] - 1, 1)];
|
||||
encodedSignature = sig;
|
||||
}
|
||||
if ( (sigData = b64decode(encodedSignature)) == nil ) goto validate_end; // Decode signature
|
||||
|
||||
// Verify the signature on the file
|
||||
result = cdsaVerifySignature( cspHandle, pubKey, hashData, (CFDataRef)sigData );
|
||||
|
||||
validate_end:
|
||||
cdsaReleaseKey( pubKey );
|
||||
cdsaRelease( cspHandle );
|
||||
if ( hashData ) CFRelease( hashData );
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Misc Helper Functions
|
||||
#pragma mark -
|
||||
|
||||
static NSData *b64decode( NSString *str )
|
||||
{
|
||||
if ( !str ) return nil;
|
||||
NSMutableData *retval = nil;
|
||||
NSData *input = [str dataUsingEncoding:NSUTF8StringEncoding];
|
||||
UInt8 *ibuf = (UInt8 *)[input bytes], *buf = NULL, *a = NULL;
|
||||
size_t len = [input length], i = 0, j = 0, size = ((len + 3) / 4) * 3;
|
||||
static UInt8 table[256] = {
|
||||
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* 00-0F */
|
||||
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* 10-1F */
|
||||
99,99,99,99,99,99,99,99,99,99,99,62,99,99,99,63, /* 20-2F */
|
||||
52,53,54,55,56,57,58,59,60,61,99,99,99,99,99,99, /* 30-3F */
|
||||
99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 40-4F */
|
||||
15,16,17,18,19,20,21,22,23,24,25,99,99,99,99,99, /* 50-5F */
|
||||
99,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* 60-6F */
|
||||
41,42,43,44,45,46,47,48,49,50,51,99,99,99,99,99, /* 70-7F */
|
||||
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* 80-8F */
|
||||
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* 90-9F */
|
||||
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* A0-AF */
|
||||
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* B0-BF */
|
||||
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* C0-CF */
|
||||
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* D0-DF */
|
||||
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, /* E0-EF */
|
||||
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99 /* F0-FF */
|
||||
};
|
||||
|
||||
retval = [NSMutableData dataWithLength:size];
|
||||
buf = [retval mutableBytes];
|
||||
|
||||
if ( (a = calloc(4, sizeof(UInt8))) == NULL ) return nil;
|
||||
|
||||
do {
|
||||
size_t ai = 0;
|
||||
a[0] = a[1] = a[2] = a[3] = 0;
|
||||
do {
|
||||
UInt8 d = table[ibuf[i++]];
|
||||
if ( d != 99 ) {
|
||||
a[ai] = d;
|
||||
ai++;
|
||||
if ( ai == 4 ) break;
|
||||
}
|
||||
} while ( i < len );
|
||||
if ( ai >= 2 ) buf[j] = (a[0] << 2) | (a[1] >> 4);
|
||||
if ( ai >= 3 ) buf[j+1] = (a[1] << 4) | (a[2] >> 2);
|
||||
if ( ai >= 4 ) buf[j+2] = (a[2] << 6) | a[3];
|
||||
j += ai-1;
|
||||
} while ( i < len );
|
||||
|
||||
free( a );
|
||||
if ( j < size ) [retval setLength:j];
|
||||
|
||||
return retval;
|
||||
}
|
||||
|
||||
static NSData *rawKeyData( NSString *key )
|
||||
{
|
||||
if ( (key == nil) || ([key length] == 0) ) return nil;
|
||||
NSMutableString *t = [[key mutableCopy] autorelease];
|
||||
|
||||
// Remove the PEM guards (if present)
|
||||
[t replaceOccurrencesOfString:@"-" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [t length])];
|
||||
[t replaceOccurrencesOfString:@"BEGIN PUBLIC KEY" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [t length])];
|
||||
[t replaceOccurrencesOfString:@"END PUBLIC KEY" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [t length])];
|
||||
|
||||
// Remove any line feeds from the beginning of the key
|
||||
while ( [t characterAtIndex:0] == '\n' ) {
|
||||
[t deleteCharactersInRange:NSMakeRange(0, 1)];
|
||||
}
|
||||
|
||||
// Remove any line feeds at the end of the key
|
||||
while ( [t characterAtIndex:[t length] - 1] == '\n' ) {
|
||||
[t deleteCharactersInRange:NSMakeRange([t length] - 1, 1)];
|
||||
}
|
||||
|
||||
// Remove whitespace around each line of the key.
|
||||
NSMutableArray *pkeyTrimmedLines = [NSMutableArray array];
|
||||
NSEnumerator *pkeyLinesEnumerator = [[t componentsSeparatedByString:@"\n"] objectEnumerator];
|
||||
NSCharacterSet *whiteSet = [NSCharacterSet whitespaceCharacterSet];
|
||||
NSString *pkeyLine;
|
||||
while ((pkeyLine = [pkeyLinesEnumerator nextObject]) != nil)
|
||||
{
|
||||
[pkeyTrimmedLines addObject:[pkeyLine stringByTrimmingCharactersInSet:whiteSet]];
|
||||
}
|
||||
key = [pkeyTrimmedLines componentsJoinedByString:@"\n"]; // Put them back together.
|
||||
|
||||
// Base64 decode to return the raw key bits (DER format rather than PEM)
|
||||
return b64decode( key );
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark CDSA
|
||||
#pragma mark -
|
||||
|
||||
/* Helper Functions */
|
||||
static CSSM_DATA_PTR su_createData( CFDataRef bytes );
|
||||
static void su_freeData( CSSM_DATA_PTR data, Boolean freeData );
|
||||
static Boolean su_copyBytesToData( CSSM_DATA_PTR data, CSSM_SIZE size, const uint8 *bytes );
|
||||
|
||||
/* Memory functions */
|
||||
static void *su_malloc( CSSM_SIZE size, void *ref );
|
||||
static void su_free( void *ptr, void *ref );
|
||||
static void *su_realloc( void *ptr, CSSM_SIZE size, void *ref );
|
||||
static void *su_calloc( uint32 num, CSSM_SIZE size, void *ref );
|
||||
|
||||
/* Constants & Typedefs */
|
||||
static CSSM_VERSION vers = { 2, 0 };
|
||||
static const CSSM_GUID su_guid = { 'S', 'p', 'a', { 'r', 'k', 'l', 'e', 0, 0, 0, 0 } };
|
||||
static CSSM_BOOL cssmInited = CSSM_FALSE;
|
||||
|
||||
static CSSM_API_MEMORY_FUNCS SU_MemFuncs = {
|
||||
su_malloc,
|
||||
su_free,
|
||||
su_realloc,
|
||||
su_calloc,
|
||||
NULL
|
||||
};
|
||||
|
||||
static CSSM_CSP_HANDLE cdsaInit( void )
|
||||
{
|
||||
CSSM_CSP_HANDLE cspHandle = CSSM_INVALID_HANDLE;
|
||||
CSSM_RETURN crtn;
|
||||
|
||||
if ( !cssmInited ) {
|
||||
CSSM_PVC_MODE pvcPolicy = CSSM_PVC_NONE;
|
||||
crtn = CSSM_Init( &vers, CSSM_PRIVILEGE_SCOPE_NONE, &su_guid, CSSM_KEY_HIERARCHY_NONE, &pvcPolicy, NULL );
|
||||
if ( crtn ) return CSSM_INVALID_HANDLE;
|
||||
cssmInited = CSSM_TRUE;
|
||||
}
|
||||
|
||||
crtn = CSSM_ModuleLoad( &gGuidAppleCSP, CSSM_KEY_HIERARCHY_NONE, NULL, NULL );
|
||||
if ( crtn ) return CSSM_INVALID_HANDLE;
|
||||
|
||||
crtn = CSSM_ModuleAttach( &gGuidAppleCSP, &vers, &SU_MemFuncs, 0, CSSM_SERVICE_CSP, 0, CSSM_KEY_HIERARCHY_NONE, NULL, 0, NULL, &cspHandle );
|
||||
if ( crtn ) return CSSM_INVALID_HANDLE;
|
||||
|
||||
return cspHandle;
|
||||
}
|
||||
|
||||
static void cdsaRelease( CSSM_CSP_HANDLE cspHandle )
|
||||
{
|
||||
if ( CSSM_ModuleDetach(cspHandle) != CSSM_OK ) return;
|
||||
CSSM_ModuleUnload( &gGuidAppleCSP, NULL, NULL );
|
||||
}
|
||||
|
||||
static CSSM_KEY_PTR cdsaCreateKey( CFDataRef rawKey )
|
||||
{
|
||||
CSSM_KEY_PTR retval = NULL;
|
||||
|
||||
if ( !rawKey || (CFDataGetLength(rawKey) == 0) ) return NULL;
|
||||
|
||||
if ( (retval = su_malloc(sizeof(CSSM_KEY), NULL)) == NULL ) return NULL;
|
||||
|
||||
if ( !su_copyBytesToData(&(retval->KeyData), CFDataGetLength(rawKey), CFDataGetBytePtr(rawKey)) ) {
|
||||
su_free( retval, NULL );
|
||||
return NULL;
|
||||
}
|
||||
|
||||
CSSM_KEYHEADER_PTR hdr = &(retval->KeyHeader);
|
||||
|
||||
memset( hdr, 0, sizeof(CSSM_KEYHEADER) );
|
||||
|
||||
hdr->HeaderVersion = CSSM_KEYHEADER_VERSION;
|
||||
hdr->CspId = su_guid;
|
||||
hdr->BlobType = CSSM_KEYBLOB_RAW;
|
||||
hdr->Format = CSSM_KEYBLOB_RAW_FORMAT_X509;
|
||||
hdr->AlgorithmId = CSSM_ALGID_DSA;
|
||||
hdr->KeyClass = CSSM_KEYCLASS_PUBLIC_KEY;
|
||||
hdr->KeyAttr = CSSM_KEYATTR_EXTRACTABLE;
|
||||
hdr->KeyUsage = CSSM_KEYUSE_ANY;
|
||||
|
||||
return retval;
|
||||
}
|
||||
|
||||
static void cdsaReleaseKey( CSSM_KEY_PTR key )
|
||||
{
|
||||
if ( key ) {
|
||||
if ( key->KeyData.Data ) su_free( key->KeyData.Data, NULL );
|
||||
su_free( key, NULL );
|
||||
}
|
||||
}
|
||||
|
||||
BOOL cdsaVerifyKey( CSSM_CSP_HANDLE cspHandle, CSSM_KEY_PTR key )
|
||||
{
|
||||
if ( key->KeyHeader.LogicalKeySizeInBits == 0 ) {
|
||||
CSSM_RETURN crtn;
|
||||
CSSM_KEY_SIZE keySize;
|
||||
|
||||
/* This will fail if the key isn't valid */
|
||||
crtn = CSSM_QueryKeySizeInBits( cspHandle, CSSM_INVALID_HANDLE, key, &keySize );
|
||||
if ( crtn ) return NO;
|
||||
key->KeyHeader.LogicalKeySizeInBits = keySize.LogicalKeySizeInBits;
|
||||
}
|
||||
return YES;
|
||||
}
|
||||
|
||||
static BOOL cdsaVerifySignature( CSSM_CSP_HANDLE cspHandle, const CSSM_KEY_PTR key, const CFDataRef msg, const CFDataRef signature )
|
||||
{
|
||||
CSSM_CC_HANDLE ccHandle = CSSM_INVALID_HANDLE;
|
||||
CSSM_DATA_PTR plain = su_createData( msg ), cipher = su_createData( signature );
|
||||
BOOL retval = NO;
|
||||
|
||||
if ( !plain || !cipher || (CSSM_CSP_CreateSignatureContext(cspHandle, CSSM_ALGID_SHA1WithDSA, NULL, key, &ccHandle) != CSSM_OK) )
|
||||
goto verify_end;
|
||||
|
||||
retval = ( CSSM_VerifyData(ccHandle, plain, 1, CSSM_ALGID_NONE, cipher) == CSSM_OK );
|
||||
|
||||
verify_end:
|
||||
su_freeData( plain, true );
|
||||
su_freeData( cipher, true );
|
||||
if ( ccHandle ) CSSM_DeleteContext( ccHandle );
|
||||
|
||||
return retval;
|
||||
}
|
||||
|
||||
static CFDataRef cdsaCreateSHA1Digest( CSSM_CSP_HANDLE cspHandle, const CFDataRef bytes )
|
||||
{
|
||||
CSSM_CC_HANDLE ccHandle = CSSM_INVALID_HANDLE;
|
||||
CSSM_DATA_PTR data = su_createData( bytes ), dgst = su_createData( NULL );
|
||||
CFDataRef retval = NULL;
|
||||
|
||||
if ( !data || !dgst || (CSSM_CSP_CreateDigestContext(cspHandle, CSSM_ALGID_SHA1, &ccHandle) != CSSM_OK) )
|
||||
goto digest_end;
|
||||
|
||||
if ( CSSM_DigestData(ccHandle, data, 1, dgst) == CSSM_OK )
|
||||
retval = CFDataCreate( kCFAllocatorDefault, (const UInt8 *)dgst->Data, (CFIndex)dgst->Length );
|
||||
|
||||
digest_end:
|
||||
su_freeData( data, true );
|
||||
su_freeData( dgst, true );
|
||||
if ( ccHandle ) CSSM_DeleteContext( ccHandle );
|
||||
|
||||
return retval;
|
||||
}
|
||||
|
||||
/* Memory Functions */
|
||||
static void *su_malloc( CSSM_SIZE size, void *ref )
|
||||
{
|
||||
return malloc( size );
|
||||
}
|
||||
|
||||
static void su_free( void *ptr, void *ref )
|
||||
{
|
||||
free( ptr );
|
||||
}
|
||||
|
||||
static void *su_realloc( void *ptr, CSSM_SIZE size, void *ref )
|
||||
{
|
||||
return realloc( ptr, size );
|
||||
}
|
||||
|
||||
static void *su_calloc( uint32 num, CSSM_SIZE size, void *ref )
|
||||
{
|
||||
return calloc( num, size );
|
||||
}
|
||||
|
||||
/* Helper Functions */
|
||||
static CSSM_DATA_PTR su_createData( CFDataRef bytes )
|
||||
{
|
||||
CSSM_DATA_PTR data = su_malloc( sizeof(CSSM_DATA), NULL );
|
||||
if ( !data ) return NULL;
|
||||
data->Data = NULL;
|
||||
data->Length = 0;
|
||||
if ( bytes ) su_copyBytesToData( data, CFDataGetLength(bytes), CFDataGetBytePtr(bytes) );
|
||||
return data;
|
||||
}
|
||||
|
||||
static void su_freeData( CSSM_DATA_PTR data, Boolean freeData )
|
||||
{
|
||||
if ( data ) {
|
||||
if ( freeData && data->Data ) su_free( data->Data, NULL );
|
||||
su_free( data, NULL );
|
||||
}
|
||||
}
|
||||
|
||||
static Boolean su_copyBytesToData( CSSM_DATA_PTR data, CSSM_SIZE size, const uint8 *bytes )
|
||||
{
|
||||
Boolean retval = false;
|
||||
if ( size && bytes ) {
|
||||
if ( (data->Data = su_malloc(size, NULL)) ) {
|
||||
memcpy( data->Data, bytes, size );
|
||||
data->Length = size;
|
||||
retval = true;
|
||||
}
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
+180
-53
@@ -9,71 +9,198 @@
|
||||
#import "SUDiskImageUnarchiver.h"
|
||||
#import "SUUnarchiver_Private.h"
|
||||
#import "NTSynchronousTask.h"
|
||||
#import "SULog.h"
|
||||
#import <CoreServices/CoreServices.h>
|
||||
|
||||
@implementation SUDiskImageUnarchiver
|
||||
|
||||
+ (BOOL)_canUnarchiveURL:(NSURL *)URL
|
||||
+ (BOOL)canUnarchivePath:(NSString *)path
|
||||
{
|
||||
return [URL conformsToType:@"public.disk-image"];
|
||||
return [[path pathExtension] isEqualToString:@"dmg"];
|
||||
}
|
||||
|
||||
// Called on a non-main thread.
|
||||
- (void)extractDMG
|
||||
{
|
||||
|
||||
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
|
||||
|
||||
NSData *result = [NTSynchronousTask task:@"/usr/bin/hdiutil" directory:@"/" withArgs:[NSArray arrayWithObjects: @"isencrypted", archivePath, nil] input:NULL];
|
||||
if([self isEncrypted:result] && [delegate respondsToSelector:@selector(unarchiver:requiresPasswordReturnedViaInvocation:)]) {
|
||||
[self performSelectorOnMainThread:@selector(requestPasswordFromDelegate) withObject:nil waitUntilDone:NO];
|
||||
} else {
|
||||
[self extractDMGWithPassword:nil];
|
||||
}
|
||||
|
||||
[pool release];
|
||||
}
|
||||
|
||||
// Called on a non-main thread.
|
||||
- (void)extractDMGWithPassword:(NSString *)password
|
||||
{
|
||||
|
||||
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
|
||||
|
||||
BOOL mountedSuccessfully = NO;
|
||||
|
||||
SULog(@"Extracting %@ as a DMG", archivePath);
|
||||
|
||||
// get a unique mount point path
|
||||
NSString *mountPointName = nil;
|
||||
NSString *mountPoint = nil;
|
||||
FSRef tmpRef;
|
||||
do
|
||||
{
|
||||
CFUUIDRef uuid = CFUUIDCreate(NULL);
|
||||
if (uuid)
|
||||
{
|
||||
CFStringRef uuidString = CFUUIDCreateString(NULL, uuid);
|
||||
if (uuidString)
|
||||
{
|
||||
mountPoint = [@"/Volumes" stringByAppendingPathComponent:(NSString*)uuidString];
|
||||
CFRelease(uuidString);
|
||||
}
|
||||
CFRelease(uuid);
|
||||
}
|
||||
}
|
||||
while (noErr == FSPathMakeRefWithOptions((UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL));
|
||||
|
||||
NSData *promptData = nil;
|
||||
if (password) {
|
||||
NSString *data = [NSString stringWithFormat:@"%@\nyes\n", password];
|
||||
const char *bytes = [data cStringUsingEncoding:NSUTF8StringEncoding];
|
||||
NSUInteger length = [data lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
|
||||
promptData = [NSData dataWithBytes:bytes length:length];
|
||||
}
|
||||
else
|
||||
promptData = [NSData dataWithBytes:"yes\n" length:4];
|
||||
|
||||
NSArray* arguments = [NSArray arrayWithObjects:@"attach", archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen", nil];
|
||||
|
||||
NSData *output = nil;
|
||||
NSInteger taskResult = -1;
|
||||
@try
|
||||
{
|
||||
NTSynchronousTask* task = [[NTSynchronousTask alloc] init];
|
||||
|
||||
[task run:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:promptData];
|
||||
|
||||
taskResult = [task result];
|
||||
output = [[[task output] copy] autorelease];
|
||||
[task release];
|
||||
}
|
||||
@catch (NSException *localException)
|
||||
{
|
||||
goto reportError;
|
||||
}
|
||||
|
||||
if (taskResult != 0)
|
||||
{
|
||||
NSString* resultStr = output ? [[[NSString alloc] initWithData: output encoding: NSUTF8StringEncoding] autorelease] : nil;
|
||||
if (password != nil && [resultStr rangeOfString:@"Authentication error"].location != NSNotFound && [delegate respondsToSelector:@selector(unarchiver:requiresPasswordReturnedViaInvocation:)]) {
|
||||
[self performSelectorOnMainThread:@selector(requestPasswordFromDelegate) withObject:nil waitUntilDone:NO];
|
||||
goto finally;
|
||||
} else {
|
||||
SULog( @"hdiutil failed with code: %d data: <<%@>>", taskResult, resultStr );
|
||||
goto reportError;
|
||||
}
|
||||
}
|
||||
mountedSuccessfully = YES;
|
||||
|
||||
// Now that we've mounted it, we need to copy out its contents.
|
||||
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) {
|
||||
// On 10.7 and later we don't want to use the File Manager API and instead want to use NSFileManager (fixes #827357).
|
||||
NSFileManager *manager = [[[NSFileManager alloc] init] autorelease];
|
||||
NSError *error = nil;
|
||||
NSArray *contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error];
|
||||
if (error)
|
||||
{
|
||||
SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error);
|
||||
goto reportError;
|
||||
}
|
||||
|
||||
NSEnumerator *contentsEnumerator = [contents objectEnumerator];
|
||||
NSString *item;
|
||||
while ((item = [contentsEnumerator nextObject]))
|
||||
{
|
||||
NSString *fromPath = [mountPoint stringByAppendingPathComponent:item];
|
||||
NSString *toPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item];
|
||||
|
||||
// We skip any files in the DMG which are not readable.
|
||||
if (![manager isReadableFileAtPath:fromPath])
|
||||
continue;
|
||||
|
||||
SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath);
|
||||
|
||||
if (![manager copyItemAtPath:fromPath toPath:toPath error:&error])
|
||||
{
|
||||
SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @"");
|
||||
goto reportError;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
FSRef srcRef, dstRef;
|
||||
OSStatus err;
|
||||
err = FSPathMakeRef((UInt8 *)[mountPoint fileSystemRepresentation], &srcRef, NULL);
|
||||
if (err != noErr) goto reportError;
|
||||
err = FSPathMakeRef((UInt8 *)[[archivePath stringByDeletingLastPathComponent] fileSystemRepresentation], &dstRef, NULL);
|
||||
if (err != noErr) goto reportError;
|
||||
|
||||
err = FSCopyObjectSync(&srcRef, &dstRef, (CFStringRef)mountPointName, NULL, kFSFileOperationSkipSourcePermissionErrors);
|
||||
if (err != noErr) goto reportError;
|
||||
}
|
||||
|
||||
[self performSelectorOnMainThread:@selector(notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO];
|
||||
goto finally;
|
||||
|
||||
reportError:
|
||||
[self performSelectorOnMainThread:@selector(notifyDelegateOfFailure) withObject:nil waitUntilDone:NO];
|
||||
|
||||
finally:
|
||||
if (mountedSuccessfully)
|
||||
[NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:[NSArray arrayWithObjects:@"detach", mountPoint, @"-force", nil]];
|
||||
else
|
||||
SULog(@"Can't mount DMG %@",archivePath);
|
||||
[pool drain];
|
||||
}
|
||||
|
||||
- (void)start
|
||||
{
|
||||
[NSThread detachNewThreadSelector:@selector(_extractDMG) toTarget:self withObject:nil];
|
||||
}
|
||||
|
||||
- (void)_extractDMG
|
||||
{
|
||||
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
|
||||
NSString *archivePath = [archiveURL path];
|
||||
BOOL mountedSuccessfully = NO;
|
||||
|
||||
// get a unique mount point path
|
||||
NSString *mountPrefix = [@"/Volumes" stringByAppendingPathComponent:[[archivePath lastPathComponent] stringByDeletingPathExtension]];
|
||||
NSString *mountPoint = [mountPrefix stringByAppendingString:[[NSProcessInfo processInfo] globallyUniqueString]];
|
||||
|
||||
if ([[NSFileManager defaultManager] fileExistsAtPath:mountPoint]) goto reportError;
|
||||
|
||||
// create mount point folder
|
||||
[[NSFileManager defaultManager] createDirectoryAtPath:mountPoint attributes:nil];
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:mountPoint]) goto reportError;
|
||||
|
||||
NSArray* arguments = [NSArray arrayWithObjects:@"attach", archivePath, @"-mountpoint", mountPoint, @"-noverify", @"-nobrowse", @"-noautoopen", nil];
|
||||
// set up a pipe and push "yes" (y works too), this will accept any license agreement crap
|
||||
// not every .dmg needs this, but this will make sure it works with everyone
|
||||
NSData* yesData = [[[NSData alloc] initWithBytes:"yes\n" length:4] autorelease];
|
||||
|
||||
NSData *result = [NTSynchronousTask task:@"/usr/bin/hdiutil" directory:@"/" withArgs:arguments input:yesData];
|
||||
if (!result) goto reportError;
|
||||
mountedSuccessfully = YES;
|
||||
|
||||
// Now that we've mounted it, we need to copy out its contents.
|
||||
NSString *targetPath = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[mountPoint lastPathComponent]];
|
||||
if (![[NSFileManager defaultManager] createDirectoryAtPath:targetPath attributes:nil]) goto reportError;
|
||||
|
||||
// We can't just copyPath: from the volume root because that always fails. Seems to be a bug.
|
||||
id subpathEnumerator = [[[NSFileManager defaultManager] directoryContentsAtPath:mountPoint] objectEnumerator], currentSubpath;
|
||||
while ((currentSubpath = [subpathEnumerator nextObject]))
|
||||
{
|
||||
if (![[NSFileManager defaultManager] copyPath:[mountPoint stringByAppendingPathComponent:currentSubpath] toPath:[targetPath stringByAppendingPathComponent:currentSubpath] handler:nil])
|
||||
goto reportError;
|
||||
}
|
||||
|
||||
[self performSelectorOnMainThread:@selector(_notifyDelegateOfSuccess) withObject:nil waitUntilDone:NO];
|
||||
goto finally;
|
||||
|
||||
reportError:
|
||||
[self performSelectorOnMainThread:@selector(_notifyDelegateOfFailure) withObject:nil waitUntilDone:NO];
|
||||
|
||||
finally:
|
||||
if (mountedSuccessfully)
|
||||
[NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:[NSArray arrayWithObjects:@"detach", mountPoint, @"-force", nil]];
|
||||
[pool drain];
|
||||
[NSThread detachNewThreadSelector:@selector(extractDMG) toTarget:self withObject:nil];
|
||||
}
|
||||
|
||||
+ (void)load
|
||||
{
|
||||
[self _registerImplementation:self];
|
||||
[self registerImplementation:self];
|
||||
}
|
||||
|
||||
- (BOOL)isEncrypted:(NSData*)resultData
|
||||
{
|
||||
BOOL result = NO;
|
||||
if(resultData)
|
||||
{
|
||||
NSString *data = [NSString stringWithCString:(char*)[resultData bytes] encoding:NSUTF8StringEncoding];
|
||||
if (!NSEqualRanges([data rangeOfString:@"passphrase-count"], NSMakeRange(NSNotFound, 0)))
|
||||
{
|
||||
result = YES;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
- (void)requestPasswordFromDelegate
|
||||
{
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(continueWithPassword:)]];
|
||||
[invocation setSelector:@selector(continueWithPassword:)];
|
||||
[invocation setTarget:self];
|
||||
[invocation retainArguments];
|
||||
[delegate unarchiver:self requiresPasswordReturnedViaInvocation:invocation];
|
||||
}
|
||||
|
||||
- (void)continueWithPassword:(NSString *)password
|
||||
{
|
||||
[NSThread detachNewThreadSelector:@selector(extractDMGWithPassword:) toTarget:self withObject:password];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,45 @@
|
||||
//
|
||||
// SUHost.h
|
||||
// Sparkle
|
||||
//
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUUpdater.h"
|
||||
#import "SUAppcast.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
|
||||
@interface SUHost : NSObject
|
||||
{
|
||||
@private
|
||||
NSBundle *bundle;
|
||||
NSString *defaultsDomain;
|
||||
BOOL usesStandardUserDefaults;
|
||||
}
|
||||
|
||||
+ (NSString *)systemVersionString;
|
||||
|
||||
- (id)initWithBundle:(NSBundle *)aBundle;
|
||||
- (NSBundle *)bundle;
|
||||
- (NSString *)bundlePath;
|
||||
- (NSString *)appSupportPath;
|
||||
- (NSString *)installationPath;
|
||||
- (NSString *)name;
|
||||
- (NSString *)version;
|
||||
- (NSString *)displayVersion;
|
||||
- (NSImage *)icon;
|
||||
- (BOOL)isRunningOnReadOnlyVolume;
|
||||
- (BOOL)isBackgroundApplication;
|
||||
- (NSString *)publicDSAKey;
|
||||
- (NSArray *)systemProfile;
|
||||
|
||||
- (id)objectForInfoDictionaryKey:(NSString *)key;
|
||||
- (BOOL)boolForInfoDictionaryKey:(NSString *)key;
|
||||
- (id)objectForUserDefaultsKey:(NSString *)defaultName;
|
||||
- (void)setObject:(id)value forUserDefaultsKey:(NSString *)defaultName;
|
||||
- (BOOL)boolForUserDefaultsKey:(NSString *)defaultName;
|
||||
- (void)setBool:(BOOL)value forUserDefaultsKey:(NSString *)defaultName;
|
||||
- (id)objectForKey:(NSString *)key;
|
||||
- (BOOL)boolForKey:(NSString *)key;
|
||||
@end
|
||||
@@ -0,0 +1,270 @@
|
||||
//
|
||||
// SUHost.m
|
||||
// Sparkle
|
||||
//
|
||||
// Copyright 2008 Andy Matuschak. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUHost.h"
|
||||
|
||||
#import "SUConstants.h"
|
||||
#import "SUSystemProfiler.h"
|
||||
#import <sys/mount.h> // For statfs for isRunningOnReadOnlyVolume
|
||||
#import "SULog.h"
|
||||
|
||||
|
||||
@implementation SUHost
|
||||
|
||||
- (id)initWithBundle:(NSBundle *)aBundle
|
||||
{
|
||||
if ((self = [super init]))
|
||||
{
|
||||
if (aBundle == nil) aBundle = [NSBundle mainBundle];
|
||||
bundle = [aBundle retain];
|
||||
if (![bundle bundleIdentifier])
|
||||
SULog(@"Sparkle Error: the bundle being updated at %@ has no CFBundleIdentifier! This will cause preference read/write to not work properly.", bundle);
|
||||
|
||||
defaultsDomain = [[bundle objectForInfoDictionaryKey:SUDefaultsDomainKey] retain];
|
||||
if (!defaultsDomain)
|
||||
defaultsDomain = [[bundle bundleIdentifier] retain];
|
||||
|
||||
// If we're using the main bundle's defaults we'll use the standard user defaults mechanism, otherwise we have to get CF-y.
|
||||
usesStandardUserDefaults = [defaultsDomain isEqualToString:[[NSBundle mainBundle] bundleIdentifier]];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[defaultsDomain release];
|
||||
[bundle release];
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@, %@>", [self class], [self bundlePath], [self installationPath]]; }
|
||||
|
||||
- (NSBundle *)bundle
|
||||
{
|
||||
return bundle;
|
||||
}
|
||||
|
||||
- (NSString *)bundlePath
|
||||
{
|
||||
return [bundle bundlePath];
|
||||
}
|
||||
|
||||
- (NSString *)appSupportPath
|
||||
{
|
||||
NSArray *appSupportPaths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
|
||||
NSString *appSupportPath = nil;
|
||||
if (!appSupportPaths || [appSupportPaths count] == 0)
|
||||
{
|
||||
SULog(@"Failed to find app support directory! Using ~/Library/Application Support...");
|
||||
appSupportPath = [@"~/Library/Application Support" stringByExpandingTildeInPath];
|
||||
}
|
||||
else
|
||||
appSupportPath = [appSupportPaths objectAtIndex:0];
|
||||
appSupportPath = [appSupportPath stringByAppendingPathComponent:[self name]];
|
||||
return appSupportPath;
|
||||
}
|
||||
|
||||
- (NSString *)installationPath
|
||||
{
|
||||
#if NORMALIZE_INSTALLED_APP_NAME
|
||||
// We'll install to "#{CFBundleName}.app", but only if that path doesn't already exist. If we're "Foo 4.2.app," and there's a "Foo.app" in this directory, we don't want to overwrite it! But if there's no "Foo.app," we'll take that name.
|
||||
NSString *normalizedAppPath = [[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent: [NSString stringWithFormat: @"%@.%@", [bundle objectForInfoDictionaryKey:@"CFBundleName"], [[bundle bundlePath] pathExtension]]];
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:[[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent: [NSString stringWithFormat: @"%@.%@", [bundle objectForInfoDictionaryKey:@"CFBundleName"], [[bundle bundlePath] pathExtension]]]])
|
||||
return normalizedAppPath;
|
||||
#endif
|
||||
return [bundle bundlePath];
|
||||
}
|
||||
|
||||
- (NSString *)name
|
||||
{
|
||||
NSString *name = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
|
||||
if (name) return name;
|
||||
|
||||
name = [self objectForInfoDictionaryKey:@"CFBundleName"];
|
||||
if (name) return name;
|
||||
|
||||
return [[[NSFileManager defaultManager] displayNameAtPath:[bundle bundlePath]] stringByDeletingPathExtension];
|
||||
}
|
||||
|
||||
- (NSString *)version
|
||||
{
|
||||
NSString *version = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"];
|
||||
if (!version || [version isEqualToString:@""])
|
||||
[NSException raise:@"SUNoVersionException" format:@"This host (%@) has no CFBundleVersion! This attribute is required.", [self bundlePath]];
|
||||
return version;
|
||||
}
|
||||
|
||||
- (NSString *)displayVersion
|
||||
{
|
||||
NSString *shortVersionString = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
|
||||
if (shortVersionString)
|
||||
return shortVersionString;
|
||||
else
|
||||
return [self version]; // Fall back on the normal version string.
|
||||
}
|
||||
|
||||
- (NSImage *)icon
|
||||
{
|
||||
// Cache the application icon.
|
||||
NSString *iconPath = [bundle pathForResource:[bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"];
|
||||
// According to the OS X docs, "CFBundleIconFile - This key identifies the file containing
|
||||
// the icon for the bundle. The filename you specify does not need to include the .icns
|
||||
// extension, although it may."
|
||||
//
|
||||
// However, if it *does* include the '.icns' the above method fails (tested on OS X 10.3.9) so we'll also try:
|
||||
if (!iconPath)
|
||||
iconPath = [bundle pathForResource:[bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType: nil];
|
||||
NSImage *icon = [[[NSImage alloc] initWithContentsOfFile:iconPath] autorelease];
|
||||
// Use a default icon if none is defined.
|
||||
if (!icon) {
|
||||
BOOL isMainBundle = (bundle == [NSBundle mainBundle]);
|
||||
|
||||
// Starting with 10.6, iconForFileType: accepts a UTI.
|
||||
NSString *fileType = nil;
|
||||
if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_5)
|
||||
fileType = isMainBundle ? NSFileTypeForHFSTypeCode(kGenericApplicationIcon) : @".bundle";
|
||||
else
|
||||
fileType = isMainBundle ? (NSString*)kUTTypeApplication : (NSString*)kUTTypeBundle;
|
||||
icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType];
|
||||
}
|
||||
return icon;
|
||||
}
|
||||
|
||||
- (BOOL)isRunningOnReadOnlyVolume
|
||||
{
|
||||
struct statfs statfs_info;
|
||||
statfs([[bundle bundlePath] fileSystemRepresentation], &statfs_info);
|
||||
return (statfs_info.f_flags & MNT_RDONLY);
|
||||
}
|
||||
|
||||
- (BOOL)isBackgroundApplication
|
||||
{
|
||||
ProcessSerialNumber PSN;
|
||||
GetCurrentProcess(&PSN);
|
||||
CFDictionaryRef processInfo = ProcessInformationCopyDictionary(&PSN, kProcessDictionaryIncludeAllInformationMask);
|
||||
BOOL isElement = [[(NSDictionary *)processInfo objectForKey:@"LSUIElement"] boolValue];
|
||||
if (processInfo)
|
||||
CFRelease(processInfo);
|
||||
return isElement;
|
||||
}
|
||||
|
||||
- (NSString *)publicDSAKey
|
||||
{
|
||||
// Maybe the key is just a string in the Info.plist.
|
||||
NSString *key = [bundle objectForInfoDictionaryKey:SUPublicDSAKeyKey];
|
||||
if (key) { return key; }
|
||||
|
||||
// More likely, we've got a reference to a Resources file by filename:
|
||||
NSString *keyFilename = [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey];
|
||||
if (!keyFilename) { return nil; }
|
||||
NSError *ignoreErr = nil;
|
||||
return [NSString stringWithContentsOfFile:[bundle pathForResource:keyFilename ofType:nil] encoding:NSASCIIStringEncoding error: &ignoreErr];
|
||||
}
|
||||
|
||||
- (NSArray *)systemProfile
|
||||
{
|
||||
return [[SUSystemProfiler sharedSystemProfiler] systemProfileArrayForHost:self];
|
||||
}
|
||||
|
||||
- (id)objectForInfoDictionaryKey:(NSString *)key
|
||||
{
|
||||
return [bundle objectForInfoDictionaryKey:key];
|
||||
}
|
||||
|
||||
- (BOOL)boolForInfoDictionaryKey:(NSString *)key
|
||||
{
|
||||
return [[self objectForInfoDictionaryKey:key] boolValue];
|
||||
}
|
||||
|
||||
- (id)objectForUserDefaultsKey:(NSString *)defaultName
|
||||
{
|
||||
// Under Tiger, CFPreferencesCopyAppValue doesn't get values from NSRegistrationDomain, so anything
|
||||
// passed into -[NSUserDefaults registerDefaults:] is ignored. The following line falls
|
||||
// back to using NSUserDefaults, but only if the host bundle is the main bundle.
|
||||
if (usesStandardUserDefaults)
|
||||
return [[NSUserDefaults standardUserDefaults] objectForKey:defaultName];
|
||||
|
||||
CFPropertyListRef obj = CFPreferencesCopyAppValue((CFStringRef)defaultName, (CFStringRef)defaultsDomain);
|
||||
return [(id)CFMakeCollectable(obj) autorelease];
|
||||
}
|
||||
|
||||
- (void)setObject:(id)value forUserDefaultsKey:(NSString *)defaultName;
|
||||
{
|
||||
if (usesStandardUserDefaults)
|
||||
{
|
||||
[[NSUserDefaults standardUserDefaults] setObject:value forKey:defaultName];
|
||||
}
|
||||
else
|
||||
{
|
||||
CFPreferencesSetValue((CFStringRef)defaultName, value, (CFStringRef)defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
|
||||
CFPreferencesSynchronize((CFStringRef)defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)boolForUserDefaultsKey:(NSString *)defaultName
|
||||
{
|
||||
if (usesStandardUserDefaults)
|
||||
return [[NSUserDefaults standardUserDefaults] boolForKey:defaultName];
|
||||
|
||||
BOOL value;
|
||||
CFPropertyListRef plr = CFPreferencesCopyAppValue((CFStringRef)defaultName, (CFStringRef)defaultsDomain);
|
||||
if (plr == NULL)
|
||||
value = NO;
|
||||
else
|
||||
{
|
||||
value = (BOOL)CFBooleanGetValue((CFBooleanRef)plr);
|
||||
CFRelease(plr);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
- (void)setBool:(BOOL)value forUserDefaultsKey:(NSString *)defaultName
|
||||
{
|
||||
if (usesStandardUserDefaults)
|
||||
{
|
||||
[[NSUserDefaults standardUserDefaults] setBool:value forKey:defaultName];
|
||||
}
|
||||
else
|
||||
{
|
||||
CFPreferencesSetValue((CFStringRef)defaultName, (CFBooleanRef)[NSNumber numberWithBool:value], (CFStringRef)defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
|
||||
CFPreferencesSynchronize((CFStringRef)defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
|
||||
}
|
||||
}
|
||||
|
||||
- (id)objectForKey:(NSString *)key {
|
||||
return [self objectForUserDefaultsKey:key] ? [self objectForUserDefaultsKey:key] : [self objectForInfoDictionaryKey:key];
|
||||
}
|
||||
|
||||
- (BOOL)boolForKey:(NSString *)key {
|
||||
return [self objectForUserDefaultsKey:key] ? [self boolForUserDefaultsKey:key] : [self boolForInfoDictionaryKey:key];
|
||||
}
|
||||
|
||||
+ (NSString *)systemVersionString
|
||||
{
|
||||
// This returns a version string of the form X.Y.Z
|
||||
// There may be a better way to deal with the problem that gestaltSystemVersionMajor
|
||||
// et al. are not defined in 10.3, but this is probably good enough.
|
||||
NSString* verStr = nil;
|
||||
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4
|
||||
SInt32 major, minor, bugfix;
|
||||
OSErr err1 = Gestalt(gestaltSystemVersionMajor, &major);
|
||||
OSErr err2 = Gestalt(gestaltSystemVersionMinor, &minor);
|
||||
OSErr err3 = Gestalt(gestaltSystemVersionBugFix, &bugfix);
|
||||
if (!err1 && !err2 && !err3)
|
||||
{
|
||||
verStr = [NSString stringWithFormat:@"%ld.%ld.%ld", (long)major, (long)minor, (long)bugfix];
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
NSString *versionPlistPath = @"/System/Library/CoreServices/SystemVersion.plist";
|
||||
verStr = [[NSDictionary dictionaryWithContentsOfFile:versionPlistPath] objectForKey:@"ProductVersion"];
|
||||
}
|
||||
return verStr;
|
||||
}
|
||||
|
||||
@end
|
||||
+9
-4
@@ -10,15 +10,20 @@
|
||||
#define SUINSTALLER_H
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
|
||||
@class SUHost;
|
||||
@interface SUInstaller : NSObject { }
|
||||
+ (void)installFromUpdateFolder:(NSString *)updateFolder overHostBundle:(NSBundle *)hostBundle delegate:delegate synchronously:(BOOL)synchronously;
|
||||
+ (void)_finishInstallationWithResult:(BOOL)result hostBundle:(NSBundle *)hostBundle error:(NSError *)error delegate:delegate;
|
||||
+ (NSString *) appPathInUpdateFolder:(NSString *)updateFolder forHost:(SUHost *)host;
|
||||
+ (void) installFromUpdateFolder:(NSString *)updateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id <SUVersionComparison>)comparator;
|
||||
+ (void) finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result host:(SUHost *)host error:(NSError *)error delegate:delegate;
|
||||
+ (NSString*) updateFolder;
|
||||
+ (void) notifyDelegateOfFailure: (NSDictionary*)dict;
|
||||
@end
|
||||
|
||||
@interface NSObject (SUInstallerDelegateInformalProtocol)
|
||||
- (void)installerFinishedForHostBundle:(NSBundle *)hostBundle;
|
||||
- (void)installerForHostBundle:(NSBundle *)hostBundle failedWithError:(NSError *)error;
|
||||
- (void)installerFinishedForHost:(SUHost *)host;
|
||||
- (void)installerForHost:(SUHost *)host failedWithError:(NSError *)error;
|
||||
@end
|
||||
|
||||
#endif
|
||||
+128
-32
@@ -9,22 +9,56 @@
|
||||
#import "SUInstaller.h"
|
||||
#import "SUPlainInstaller.h"
|
||||
#import "SUPackageInstaller.h"
|
||||
#import "SUHost.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SULog.h"
|
||||
|
||||
NSString *SUInstallerPathKey = @"SUInstallerPath";
|
||||
NSString *SUInstallerHostBundleKey = @"SUInstallerHostBundle";
|
||||
NSString *SUInstallerDelegateKey = @"SUInstallerDelegate";
|
||||
|
||||
@implementation SUInstaller
|
||||
|
||||
+ (void)installFromUpdateFolder:(NSString *)updateFolder overHostBundle:(NSBundle *)hostBundle delegate:delegate synchronously:(BOOL)synchronously
|
||||
static NSString* sUpdateFolder = nil;
|
||||
|
||||
+(NSString*) updateFolder
|
||||
{
|
||||
// Search subdirectories for the application
|
||||
NSString *currentFile, *newAppDownloadPath = nil, *bundleFileName = [[hostBundle bundlePath] lastPathComponent], *alternateBundleFileName = [[hostBundle name] stringByAppendingPathExtension:[[hostBundle bundlePath] pathExtension]];
|
||||
return sUpdateFolder;
|
||||
}
|
||||
|
||||
+ (BOOL)isAliasFolderAtPath:(NSString *)path
|
||||
{
|
||||
FSRef fileRef;
|
||||
OSStatus err = noErr;
|
||||
Boolean aliasFileFlag, folderFlag;
|
||||
NSURL *fileURL = [NSURL fileURLWithPath:path];
|
||||
|
||||
if (FALSE == CFURLGetFSRef((CFURLRef)fileURL, &fileRef))
|
||||
err = coreFoundationUnknownErr;
|
||||
|
||||
if (noErr == err)
|
||||
err = FSIsAliasFile(&fileRef, &aliasFileFlag, &folderFlag);
|
||||
|
||||
if (noErr == err)
|
||||
return (BOOL)(aliasFileFlag && folderFlag);
|
||||
else
|
||||
return NO;
|
||||
}
|
||||
|
||||
+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr
|
||||
{
|
||||
// Search subdirectories for the application
|
||||
NSString *currentFile,
|
||||
*newAppDownloadPath = nil,
|
||||
*bundleFileName = [[host bundlePath] lastPathComponent],
|
||||
*alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]];
|
||||
BOOL isPackage = NO;
|
||||
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:updateFolder];
|
||||
NSString *fallbackPackagePath = nil;
|
||||
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath: inUpdateFolder];
|
||||
|
||||
[sUpdateFolder release];
|
||||
sUpdateFolder = [inUpdateFolder retain];
|
||||
|
||||
while ((currentFile = [dirEnum nextObject]))
|
||||
{
|
||||
NSString *currentPath = [updateFolder stringByAppendingPathComponent:currentFile];
|
||||
NSString *currentPath = [inUpdateFolder stringByAppendingPathComponent:currentFile];
|
||||
if ([[currentFile lastPathComponent] isEqualToString:bundleFileName] ||
|
||||
[[currentFile lastPathComponent] isEqualToString:alternateBundleFileName]) // We found one!
|
||||
{
|
||||
@@ -32,55 +66,117 @@ NSString *SUInstallerDelegateKey = @"SUInstallerDelegate";
|
||||
newAppDownloadPath = currentPath;
|
||||
break;
|
||||
}
|
||||
else if (([[currentFile pathExtension] isEqualToString:@"pkg"] || [[currentFile pathExtension] isEqualToString:@"mpkg"]) &&
|
||||
[[[currentFile lastPathComponent] stringByDeletingPathExtension] isEqualToString:[bundleFileName stringByDeletingPathExtension]])
|
||||
else if ([[currentFile pathExtension] isEqualToString:@"pkg"] ||
|
||||
[[currentFile pathExtension] isEqualToString:@"mpkg"])
|
||||
{
|
||||
isPackage = YES;
|
||||
newAppDownloadPath = currentPath;
|
||||
break;
|
||||
if ([[[currentFile lastPathComponent] stringByDeletingPathExtension] isEqualToString:[bundleFileName stringByDeletingPathExtension]])
|
||||
{
|
||||
isPackage = YES;
|
||||
newAppDownloadPath = currentPath;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Remember any other non-matching packages we have seen should we need to use one of them as a fallback.
|
||||
fallbackPackagePath = currentPath;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Try matching on bundle identifiers in case the user has changed the name of the host app
|
||||
NSBundle *incomingBundle = [NSBundle bundleWithPath:currentPath];
|
||||
if(incomingBundle && [[incomingBundle bundleIdentifier] isEqualToString:[[host bundle] bundleIdentifier]])
|
||||
{
|
||||
isPackage = NO;
|
||||
newAppDownloadPath = currentPath;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Some DMGs have symlinks into /Applications! That's no good! And there's no point in looking in bundles.
|
||||
if ([[NSFileManager defaultManager] isAliasFolderAtPath:currentPath] ||
|
||||
[[currentFile pathExtension] isEqualToString:[[hostBundle bundlePath] pathExtension]] ||
|
||||
[[currentFile pathExtension] isEqualToString:@"pkg"] ||
|
||||
[[currentFile pathExtension] isEqualToString:@"mpkg"])
|
||||
{
|
||||
// Some DMGs have symlinks into /Applications! That's no good!
|
||||
if ([self isAliasFolderAtPath:currentPath])
|
||||
[dirEnum skipDescendents];
|
||||
}
|
||||
}
|
||||
|
||||
// We don't have a valid path. Try to use the fallback package.
|
||||
|
||||
if (newAppDownloadPath == nil && fallbackPackagePath != nil)
|
||||
{
|
||||
isPackage = YES;
|
||||
newAppDownloadPath = fallbackPackagePath;
|
||||
}
|
||||
|
||||
if (isPackagePtr) *isPackagePtr = isPackage;
|
||||
return newAppDownloadPath;
|
||||
}
|
||||
|
||||
+ (NSString *)appPathInUpdateFolder:(NSString *)updateFolder forHost:(SUHost *)host
|
||||
{
|
||||
BOOL isPackage = NO;
|
||||
NSString *path = [self installSourcePathInUpdateFolder:updateFolder forHost:host isPackage:&isPackage];
|
||||
return isPackage ? nil : path;
|
||||
}
|
||||
|
||||
+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id <SUVersionComparison>)comparator
|
||||
{
|
||||
BOOL isPackage = NO;
|
||||
NSString *newAppDownloadPath = [self installSourcePathInUpdateFolder:inUpdateFolder forHost:host isPackage:&isPackage];
|
||||
|
||||
if (newAppDownloadPath == nil)
|
||||
{
|
||||
[self _finishInstallationWithResult:NO hostBundle:hostBundle error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:[NSDictionary dictionaryWithObject:@"Couldn't find an appropriate update in the downloaded package." forKey:NSLocalizedDescriptionKey]] delegate:delegate];
|
||||
[self finishInstallationToPath:installationPath withResult:NO host:host error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:[NSDictionary dictionaryWithObject:@"Couldn't find an appropriate update in the downloaded package." forKey:NSLocalizedDescriptionKey]] delegate:delegate];
|
||||
}
|
||||
else
|
||||
{
|
||||
[(isPackage ? [SUPackageInstaller class] : [SUPlainInstaller class]) performInstallationWithPath:newAppDownloadPath hostBundle:hostBundle delegate:delegate synchronously:synchronously];
|
||||
[(isPackage ? [SUPackageInstaller class] : [SUPlainInstaller class]) performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host delegate:delegate synchronously:synchronously versionComparator:comparator];
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)_mdimportBundle:(NSBundle *)bundle
|
||||
+ (void)mdimportInstallationPath:(NSString *)installationPath
|
||||
{
|
||||
// *** GETS CALLED ON NON-MAIN THREAD!
|
||||
|
||||
SULog( @"mdimporting" );
|
||||
|
||||
NSTask *mdimport = [[[NSTask alloc] init] autorelease];
|
||||
[mdimport setLaunchPath:@"/usr/bin/mdimport"];
|
||||
[mdimport setArguments:[NSArray arrayWithObject:[bundle bundlePath]]];
|
||||
[mdimport launch];
|
||||
[mdimport setArguments:[NSArray arrayWithObject:installationPath]];
|
||||
@try
|
||||
{
|
||||
[mdimport launch];
|
||||
[mdimport waitUntilExit];
|
||||
}
|
||||
@catch (NSException * launchException)
|
||||
{
|
||||
// No big deal.
|
||||
SULog(@"Sparkle Error: %@", [launchException description]);
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)_finishInstallationWithResult:(BOOL)result hostBundle:(NSBundle *)hostBundle error:(NSError *)error delegate:delegate
|
||||
|
||||
#define SUNotifyDictHostKey @"SUNotifyDictHost"
|
||||
#define SUNotifyDictErrorKey @"SUNotifyDictError"
|
||||
#define SUNotifyDictDelegateKey @"SUNotifyDictDelegate"
|
||||
|
||||
+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result host:(SUHost *)host error:(NSError *)error delegate:delegate
|
||||
{
|
||||
if (result == YES)
|
||||
if (result)
|
||||
{
|
||||
[self _mdimportBundle:hostBundle];
|
||||
if ([delegate respondsToSelector:@selector(installerFinishedForHostBundle:)])
|
||||
[delegate installerFinishedForHostBundle:hostBundle];
|
||||
[self mdimportInstallationPath:installationPath];
|
||||
if ([delegate respondsToSelector:@selector(installerFinishedForHost:)])
|
||||
[delegate performSelectorOnMainThread: @selector(installerFinishedForHost:) withObject: host waitUntilDone: NO];
|
||||
}
|
||||
else
|
||||
{
|
||||
if ([delegate respondsToSelector:@selector(installerForHostBundle:failedWithError:)])
|
||||
[delegate installerForHostBundle:hostBundle failedWithError:error];
|
||||
if ([delegate respondsToSelector:@selector(installerForHost:failedWithError:)])
|
||||
[self performSelectorOnMainThread: @selector(notifyDelegateOfFailure:) withObject: [NSDictionary dictionaryWithObjectsAndKeys: host, SUNotifyDictHostKey, error, SUNotifyDictErrorKey, delegate, SUNotifyDictDelegateKey, nil] waitUntilDone: NO];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+(void) notifyDelegateOfFailure: (NSDictionary*)dict
|
||||
{
|
||||
[[dict objectForKey: SUNotifyDictDelegateKey] installerForHost: [dict objectForKey: SUNotifyDictHostKey] failedWithError: [dict objectForKey: SUNotifyDictErrorKey]];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* SULog.h
|
||||
* EyeTV
|
||||
*
|
||||
* Created by Uli Kusterer on 12/03/2009.
|
||||
* Copyright 2008 Elgato Systems GmbH. All rights reserved.
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
Log output for troubleshooting Sparkle failures on end-user machines.
|
||||
Your tech support will hug you if you tell them about this.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Headers:
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
#include <Foundation/Foundation.h>
|
||||
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Prototypes:
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
void SUClearLog( void );
|
||||
void SULog( NSString* format, ... );
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* SULog.m
|
||||
* EyeTV
|
||||
*
|
||||
* Created by Uli Kusterer on 12/03/2009.
|
||||
* Copyright 2009 Elgato Systems GmbH. All rights reserved.
|
||||
*
|
||||
*/
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Headers:
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
#include "SULog.h"
|
||||
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Constants:
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
#define LOG_FILE_PATH @"~/Library/Logs/SparkleUpdateLog.log"
|
||||
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// SUClearLog:
|
||||
// Erase the log at the start of an update. We don't want to litter the
|
||||
// user's hard disk with logging data that's mostly unused, so each app
|
||||
// should clear the log before it starts updating, so only the most recent
|
||||
// update is kept around.
|
||||
//
|
||||
// TAKES:
|
||||
// sender - Object that sent this message, typically of type X.
|
||||
//
|
||||
// GIVES:
|
||||
// param - who owns the returned value?
|
||||
// result - same here.
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
void SUClearLog( void )
|
||||
{
|
||||
FILE* logfile = fopen([[LOG_FILE_PATH stringByExpandingTildeInPath] fileSystemRepresentation],"w");
|
||||
if( logfile )
|
||||
fclose(logfile);
|
||||
else
|
||||
NSLog(@"----- Sparkle Log -----");
|
||||
}
|
||||
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// SULog:
|
||||
// Like NSLog, but logs to one specific log file. Each line is prefixed
|
||||
// with the current date and time, to help in regressing issues.
|
||||
//
|
||||
// TAKES:
|
||||
// format - NSLog/printf-style format string.
|
||||
// ... - More parameters depending on format string's contents.
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
void SULog( NSString* format, ... )
|
||||
{
|
||||
va_list ap;
|
||||
va_start(ap, format);
|
||||
NSString* theStr = [[[NSString alloc] initWithFormat: format arguments: ap] autorelease];
|
||||
FILE* logfile = fopen([[LOG_FILE_PATH stringByExpandingTildeInPath] fileSystemRepresentation],"a");
|
||||
if( !logfile )
|
||||
NSLog( @"%@",theStr );
|
||||
else
|
||||
{
|
||||
theStr = [NSString stringWithFormat: @"%@: %@", [NSDate date], theStr];
|
||||
NSData* theData = [theStr dataUsingEncoding: NSUTF8StringEncoding];
|
||||
char newlineChar = '\n';
|
||||
fwrite( [theData bytes], 1, [theData length], logfile );
|
||||
fwrite( &newlineChar, 1, 1, logfile ); // Append a newline.
|
||||
fclose( logfile );
|
||||
logfile = NULL;
|
||||
}
|
||||
va_end(ap);
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 388 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user