-
Notifications
You must be signed in to change notification settings - Fork 339
/
updatecheck.py
executable file
·3452 lines (3058 loc) · 141 KB
/
updatecheck.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# encoding: utf-8
#
# Copyright 2009-2014 Greg Neagle.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
updatecheck
Created by Greg Neagle on 2008-11-13.
"""
# standard libs
import datetime
import os
import subprocess
import socket
import urllib2
import urlparse
from urllib import quote_plus
from OpenSSL.crypto import load_certificate, FILETYPE_PEM
# our libs
import appleupdates
import fetch
import keychain
import munkicommon
import munkistatus
import profiles
import FoundationPlist
# Apple's libs
# PyLint cannot properly find names inside Cocoa libraries, so issues bogus
# No name 'Foo' in module 'Bar' warnings. Disable them.
# pylint: disable=E0611
from Foundation import NSDate, NSPredicate, NSTimeZone
# pylint: enable=E0611
# Disable PyLint complaining about 'invalid' camelCase names
# pylint: disable=C0103
# This many hours before a force install deadline, start notifying the user.
FORCE_INSTALL_WARNING_HOURS = 4
def makeCatalogDB(catalogitems):
"""Takes an array of catalog items and builds some indexes so we can
get our common data faster. Returns a dict we can use like a database"""
name_table = {}
pkgid_table = {}
itemindex = -1
for item in catalogitems:
itemindex = itemindex + 1
name = item.get('name', 'NO NAME')
vers = item.get('version', 'NO VERSION')
if name == 'NO NAME' or vers == 'NO VERSION':
munkicommon.display_warning('Bad pkginfo: %s', item)
# normalize the version number
vers = trimVersionString(vers)
# build indexes for items by name and version
if not name in name_table:
name_table[name] = {}
if not vers in name_table[name]:
name_table[name][vers] = []
name_table[name][vers].append(itemindex)
# build table of receipts
for receipt in item.get('receipts', []):
if 'packageid' in receipt and 'version' in receipt:
pkg_id = receipt['packageid']
version = receipt['version']
if not pkg_id in pkgid_table:
pkgid_table[pkg_id] = {}
if not version in pkgid_table[pkg_id]:
pkgid_table[pkg_id][version] = []
pkgid_table[pkg_id][version].append(itemindex)
# build table of update items with a list comprehension --
# filter all items from the catalogitems that have a non-empty
# 'update_for' list
updaters = [item for item in catalogitems if item.get('update_for')]
# now fix possible admin errors where 'update_for' is a string instead
# of a list of strings
for update in updaters:
if isinstance(update['update_for'], basestring):
# convert to list of strings
update['update_for'] = [update['update_for']]
# build table of autoremove items with a list comprehension --
# filter all items from the catalogitems that have a non-empty
# 'autoremove' list
# autoremove items are automatically removed if they are not in the
# managed_install list (either directly or indirectly via included
# manifests)
autoremoveitems = [item.get('name') for item in catalogitems
if item.get('autoremove')]
# convert to set and back to list to get list of unique names
autoremoveitems = list(set(autoremoveitems))
pkgdb = {}
pkgdb['named'] = name_table
pkgdb['receipts'] = pkgid_table
pkgdb['updaters'] = updaters
pkgdb['autoremoveitems'] = autoremoveitems
pkgdb['items'] = catalogitems
return pkgdb
def addPackageids(catalogitems, itemname_to_pkgid, pkgid_to_itemname):
"""Adds packageids from each catalogitem to two dictionaries.
One maps itemnames to receipt pkgids, the other maps receipt pkgids
to itemnames"""
for item in catalogitems:
name = item.get('name')
if not name:
continue
if item.get('receipts'):
if not name in itemname_to_pkgid:
itemname_to_pkgid[name] = {}
for receipt in item['receipts']:
if 'packageid' in receipt:
pkgid = receipt['packageid']
vers = receipt['version']
if not pkgid in itemname_to_pkgid[name]:
itemname_to_pkgid[name][pkgid] = []
if not vers in itemname_to_pkgid[name][pkgid]:
itemname_to_pkgid[name][pkgid].append(vers)
if not pkgid in pkgid_to_itemname:
pkgid_to_itemname[pkgid] = {}
if not name in pkgid_to_itemname[pkgid]:
pkgid_to_itemname[pkgid][name] = []
if not vers in pkgid_to_itemname[pkgid][name]:
pkgid_to_itemname[pkgid][name].append(vers)
INSTALLEDPKGS = {}
def getInstalledPackages():
"""Builds a dictionary of installed receipts and their version number"""
#global INSTALLEDPKGS
# we use the --regexp option to pkgutil to get it to return receipt
# info for all installed packages. Huge speed up.
proc = subprocess.Popen(['/usr/sbin/pkgutil', '--regexp',
'--pkg-info-plist', '.*'], bufsize=8192,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, dummy_err) = proc.communicate()
while out:
(pliststr, out) = munkicommon.getFirstPlist(out)
if pliststr:
plist = FoundationPlist.readPlistFromString(pliststr)
if 'pkg-version' in plist and 'pkgid' in plist:
INSTALLEDPKGS[plist['pkgid']] = (
plist['pkg-version'] or '0.0.0.0.0')
else:
break
# Now check /Library/Receipts
receiptsdir = '/Library/Receipts'
if os.path.exists(receiptsdir):
installitems = munkicommon.listdir(receiptsdir)
for item in installitems:
if item.endswith('.pkg'):
pkginfo = munkicommon.getOnePackageInfo(
os.path.join(receiptsdir, item))
pkgid = pkginfo.get('packageid')
thisversion = pkginfo.get('version')
if pkgid:
if not pkgid in INSTALLEDPKGS:
INSTALLEDPKGS[pkgid] = thisversion
else:
# pkgid is already in our list. There must be
# multiple receipts with the same pkgid.
# in this case, we want the highest version
# number, since that's the one that's
# installed, since presumably
# the newer package replaced the older one
storedversion = INSTALLEDPKGS[pkgid]
if (munkicommon.MunkiLooseVersion(thisversion) >
munkicommon.MunkiLooseVersion(storedversion)):
INSTALLEDPKGS[pkgid] = thisversion
#ManagedInstallDir = munkicommon.pref('ManagedInstallDir')
#receiptsdatapath = os.path.join(ManagedInstallDir, 'FoundReceipts.plist')
#try:
# FoundationPlist.writePlist(INSTALLEDPKGS, receiptsdatapath)
#except FoundationPlist.NSPropertyListWriteException:
# pass
def bestVersionMatch(vers_num, item_dict):
'''Attempts to find the best match in item_dict for vers_num'''
vers_tuple = vers_num.split('.')
precision = 1
while precision <= len(vers_tuple):
test_vers = '.'.join(vers_tuple[0:precision])
match_names = []
for item in item_dict.keys():
for item_version in item_dict[item]:
if (item_version.startswith(test_vers) and
item not in match_names):
match_names.append(item)
if len(match_names) == 1:
return match_names[0]
precision = precision + 1
return None
# global pkgdata
PKGDATA = {}
def analyzeInstalledPkgs():
"""Analyzed installed packages in an attempt to determine what is
installed."""
#global PKGDATA
itemname_to_pkgid = {}
pkgid_to_itemname = {}
for catalogname in CATALOG.keys():
catalogitems = CATALOG[catalogname]['items']
addPackageids(catalogitems, itemname_to_pkgid, pkgid_to_itemname)
# itemname_to_pkgid now contains all receipts (pkgids) we know about
# from items in all available catalogs
if not INSTALLEDPKGS:
getInstalledPackages()
# INSTALLEDPKGS now contains all receipts found on this machine
installed = []
partiallyinstalled = []
installedpkgsmatchedtoname = {}
for name in itemname_to_pkgid.keys():
# name is a Munki install item name
somepkgsfound = False
allpkgsfound = True
for pkgid in itemname_to_pkgid[name].keys():
if pkgid in INSTALLEDPKGS.keys():
somepkgsfound = True
if not name in installedpkgsmatchedtoname:
installedpkgsmatchedtoname[name] = []
# record this pkgid for Munki install item name
installedpkgsmatchedtoname[name].append(pkgid)
else:
# didn't find pkgid in INSTALLEDPKGS
allpkgsfound = False
if allpkgsfound:
# we found all receipts by pkgid on disk
installed.append(name)
elif somepkgsfound:
# we found only some receipts for the item
# on disk
partiallyinstalled.append(name)
# we pay special attention to the items that seem partially installed.
# we need to see if there are any packages that are unique to this item
# if there aren't, then this item probably isn't installed, and we're
# just finding receipts that are shared with other items.
for name in partiallyinstalled:
# get a list of pkgs for this item that are installed
pkgsforthisname = installedpkgsmatchedtoname[name]
# now build a list of all the pkgs referred to by all the other
# items that are either partially or entirely installed
allotherpkgs = []
for othername in installed:
allotherpkgs.extend(installedpkgsmatchedtoname[othername])
for othername in partiallyinstalled:
if othername != name:
allotherpkgs.extend(installedpkgsmatchedtoname[othername])
# use Python sets to find pkgs that are unique to this name
uniquepkgs = list(set(pkgsforthisname) - set(allotherpkgs))
if uniquepkgs:
installed.append(name)
# now filter partiallyinstalled to remove those items we moved to installed
partiallyinstalled = [item for item in partiallyinstalled
if item not in installed]
# build our reference table. For each item we think is installed,
# record the receipts on disk matched to the item
references = {}
for name in installed:
for pkgid in installedpkgsmatchedtoname[name]:
if not pkgid in references:
references[pkgid] = []
references[pkgid].append(name)
# look through all our INSTALLEDPKGS, looking for ones that have not been
# attached to any Munki names yet
orphans = [pkgid for pkgid in INSTALLEDPKGS.keys()
if pkgid not in references]
# attempt to match orphans to Munki item names
matched_orphans = []
for pkgid in orphans:
if pkgid in pkgid_to_itemname:
installed_pkgid_version = INSTALLEDPKGS[pkgid]
possible_match_items = pkgid_to_itemname[pkgid]
best_match = bestVersionMatch(
installed_pkgid_version, possible_match_items)
if best_match:
matched_orphans.append(best_match)
# process matched_orphans
for name in matched_orphans:
if name not in installed:
installed.append(name)
if name in partiallyinstalled:
partiallyinstalled.remove(name)
for pkgid in installedpkgsmatchedtoname[name]:
if not pkgid in references:
references[pkgid] = []
if not name in references[pkgid]:
references[pkgid].append(name)
PKGDATA['receipts_for_name'] = installedpkgsmatchedtoname
PKGDATA['installed_names'] = installed
PKGDATA['pkg_references'] = references
# left here for future debugging/testing use....
#PKGDATA['itemname_to_pkgid'] = itemname_to_pkgid
#PKGDATA['pkgid_to_itemname'] = pkgid_to_itemname
#PKGDATA['partiallyinstalled_names'] = partiallyinstalled
#PKGDATA['orphans'] = orphans
#PKGDATA['matched_orphans'] = matched_orphans
#ManagedInstallDir = munkicommon.pref('ManagedInstallDir')
#pkgdatapath = os.path.join(ManagedInstallDir, 'PackageData.plist')
#try:
# FoundationPlist.writePlist(PKGDATA, pkgdatapath)
#except FoundationPlist.NSPropertyListWriteException:
# pass
#catalogdbpath = os.path.join(ManagedInstallDir, 'CatalogDB.plist')
#try:
# FoundationPlist.writePlist(CATALOG, catalogdbpath)
#except FoundationPlist.NSPropertyListWriteException:
# pass
def getAppBundleID(path):
"""Returns CFBundleIdentifier if available for application at path."""
infopath = os.path.join(path, 'Contents', 'Info.plist')
if os.path.exists(infopath):
try:
plist = FoundationPlist.readPlist(infopath)
if 'CFBundleIdentifier' in plist:
return plist['CFBundleIdentifier']
except (AttributeError,
FoundationPlist.NSPropertyListSerializationException):
pass
return None
def compareVersions(thisvers, thatvers):
"""Compares two version numbers to one another.
Returns:
-1 if thisvers is older than thatvers
1 if thisvers is the same as thatvers
2 if thisvers is newer than thatvers
"""
if (munkicommon.MunkiLooseVersion(thisvers) <
munkicommon.MunkiLooseVersion(thatvers)):
return -1
elif (munkicommon.MunkiLooseVersion(thisvers) ==
munkicommon.MunkiLooseVersion(thatvers)):
return 1
else:
return 2
def compareApplicationVersion(app):
"""First checks the given path if it's available,
then uses system profiler data to look for the app
Args:
app: dict with application bundle info
Returns:
Boolean.
0 if the app isn't installed
or doesn't have valid Info.plist
-1 if it's older
1 if the version is the same
2 if the version is newer
Raises munkicommon.Error if there's an error in the input
"""
if 'path' in app:
filepath = os.path.join(app['path'], 'Contents', 'Info.plist')
if os.path.exists(filepath):
return compareBundleVersion(app)
# not in default location, or no path specified, so let's search:
name = app.get('CFBundleName', '')
bundleid = app.get('CFBundleIdentifier', '')
version_comparison_key = app.get(
'version_comparison_key', 'CFBundleShortVersionString')
versionstring = app.get(version_comparison_key)
minupvers = app.get('minimum_update_version')
if name == '' and bundleid == '':
if 'path' in app:
# already looked at default path, and we don't have
# any additional info, so we have to assume it's not installed.
return 0
else:
# no path, no name, no bundleid. Error!
raise munkicommon.Error(
'No application name or bundleid was specified!')
munkicommon.display_debug1(
'Looking for application %s with bundleid: %s, version %s...' %
(name, bundleid, versionstring))
appinfo = []
appdata = munkicommon.getAppData()
if appdata:
for item in appdata:
# Skip applications in /Users but not /Users/Shared, for now.
if 'path' in item:
if item['path'].startswith('/Users/') and \
not item['path'].startswith('/Users/Shared/'):
munkicommon.display_debug2(
'Skipped app %s with path %s',
item['name'], item['path'])
continue
if bundleid:
if item['bundleid'] == bundleid:
appinfo.append(item)
elif name and item['name'] == name:
appinfo.append(item)
if not appinfo:
# app isn't present!
munkicommon.display_debug1(
'\tDid not find this application on the startup disk.')
return 0
# iterate through matching applications
for item in appinfo:
if 'name' in item:
munkicommon.display_debug2(
'\tName: \t %s', item['name'])
if 'path' in item:
apppath = item['path']
munkicommon.display_debug2(
'\tPath: \t %s', apppath)
munkicommon.display_debug2(
'\tCFBundleIdentifier: \t %s', item['bundleid'])
if apppath and version_comparison_key != 'CFBundleShortVersionString':
# if a specific plist version key has been supplied,
# if we're suppose to compare against a key other than
# 'CFBundleShortVersionString' we can't use item['version']
installed_version = munkicommon.getBundleVersion(
apppath, version_comparison_key)
else:
# item['version'] is CFBundleShortVersionString
installed_version = item['version']
if minupvers:
if compareVersions(installed_version, minupvers) < 1:
munkicommon.display_debug1(
'\tVersion %s too old < %s', installed_version, minupvers)
# installed version is < minimum_update_version,
# too old to match
return 0
if 'version' in item:
munkicommon.display_debug2(
'\tVersion: \t %s', installed_version)
if compareVersions(installed_version, versionstring) == 1:
# version is the same
return 1
if compareVersions(installed_version, versionstring) == 2:
# version is newer
return 2
# if we got this far, must only be older
munkicommon.display_debug1(
'An older version of this application is present.')
return -1
def compareBundleVersion(item):
"""Compares a bundle version passed item dict.
Returns 0 if the bundle isn't installed
or doesn't have valid Info.plist
-1 if it's older
1 if the version is the same
2 if the version is newer
Raises munkicommon.Error if there's an error in the input
"""
# look for an Info.plist inside the bundle
filepath = os.path.join(item['path'], 'Contents', 'Info.plist')
if not os.path.exists(filepath):
munkicommon.display_debug1('\tNo Info.plist found at %s', filepath)
filepath = os.path.join(item['path'], 'Resources', 'Info.plist')
if not os.path.exists(filepath):
munkicommon.display_debug1('\tNo Info.plist found at %s', filepath)
return 0
munkicommon.display_debug1('\tFound Info.plist at %s', filepath)
# just let comparePlistVersion do the comparison
saved_path = item['path']
item['path'] = filepath
compare_result = comparePlistVersion(item)
item['path'] = saved_path
return compare_result
def comparePlistVersion(item):
"""Gets the version string from the plist at path and compares versions.
Returns 0 if the plist isn't installed
-1 if it's older
1 if the version is the same
2 if the version is newer
Raises munkicommon.Error if there's an error in the input
"""
version_comparison_key = item.get(
'version_comparison_key', 'CFBundleShortVersionString')
if 'path' in item and version_comparison_key in item:
versionstring = item[version_comparison_key]
filepath = item['path']
minupvers = item.get('minimum_update_version')
else:
raise munkicommon.Error('Missing plist path or version!')
munkicommon.display_debug1('\tChecking %s for %s %s...',
filepath, version_comparison_key, versionstring)
if not os.path.exists(filepath):
munkicommon.display_debug1('\tNo plist found at %s', filepath)
return 0
try:
plist = FoundationPlist.readPlist(filepath)
except FoundationPlist.NSPropertyListSerializationException:
munkicommon.display_debug1('\t%s may not be a plist!', filepath)
return 0
if not hasattr(plist, 'get'):
munkicommon.display_debug1(
'plist not parsed as NSCFDictionary: %s', filepath)
return 0
if 'version_comparison_key' in item:
# specific key has been supplied,
# so use this to determine installed version
munkicommon.display_debug1(
'\tUsing version_comparison_key %s', version_comparison_key)
installedvers = munkicommon.getVersionString(
plist, version_comparison_key)
else:
# default behavior
installedvers = munkicommon.getVersionString(plist)
if installedvers:
munkicommon.display_debug1(
'\tInstalled item has version %s', installedvers)
if minupvers:
if compareVersions(installedvers, minupvers) < 1:
munkicommon.display_debug1(
'\tVersion %s too old < %s', installedvers, minupvers)
return 0
compare_result = compareVersions(installedvers, versionstring)
results = ['older', 'not installed?!', 'the same', 'newer']
munkicommon.display_debug1('\tInstalled item is %s.',
results[compare_result + 1])
return compare_result
else:
munkicommon.display_debug1('\tNo version info in %s.', filepath)
return 0
def filesystemItemExists(item):
"""Checks to see if a filesystem item exists.
If item has md5checksum attribute, compares on disk file's checksum.
Returns 0 if the filesystem item does not exist on disk,
Returns 1 if the filesystem item exists and the checksum matches
(or there is no checksum)
Returns -1 if the filesystem item exists but the checksum does not match.
Broken symlinks are OK; we're testing for the existence of the symlink,
not the item it points to.
Raises munkicommon.Error is there's a problem with the input.
"""
if 'path' in item:
filepath = item['path']
munkicommon.display_debug1('Checking existence of %s...', filepath)
if os.path.lexists(filepath):
munkicommon.display_debug2('\tExists.')
if 'md5checksum' in item:
storedchecksum = item['md5checksum']
ondiskchecksum = munkicommon.getmd5hash(filepath)
munkicommon.display_debug2('Comparing checksums...')
if storedchecksum == ondiskchecksum:
munkicommon.display_debug2('Checksums match.')
return 1
else:
munkicommon.display_debug2(
'Checksums differ: expected %s, got %s',
storedchecksum, ondiskchecksum)
return -1
else:
return 1
else:
munkicommon.display_debug2('\tDoes not exist.')
return 0
else:
raise munkicommon.Error('No path specified for filesystem item.')
def compareItemVersion(item):
'''Compares an installs_item with what's on the startup disk.
Wraps other comparsion functions.
For applications, bundles, and plists:
Returns 0 if the item isn't installed
or doesn't have valid Info.plist
-1 if it's older
1 if the version is the same
2 if the version is newer
For other filesystem items:
Returns 0 if the filesystem item does not exist on disk,
1 if the filesystem item exists and the checksum matches
(or there is no checksum)
-1 if the filesystem item exists but the checksum does not match.
'''
if not 'VersionString' in item and 'CFBundleShortVersionString' in item:
# Ensure that 'VersionString', if not present, is populated
# with the value of 'CFBundleShortVersionString' if present
item['VersionString'] = item['CFBundleShortVersionString']
itemtype = item.get('type')
if itemtype == 'application':
return compareApplicationVersion(item)
if itemtype == 'bundle':
return compareBundleVersion(item)
if itemtype == 'plist':
return comparePlistVersion(item)
if itemtype == 'file':
return filesystemItemExists(item)
raise munkicommon.Error('Unknown installs item type: %s', itemtype)
def compareReceiptVersion(item):
"""Determines if the given package is already installed.
Args:
item: dict with packageid; a 'com.apple.pkg.ServerAdminTools' style id
Returns 0 if the receipt isn't present
-1 if it's older
1 if the version is the same
2 if the version is newer
Raises munkicommon.Error if there's an error in the input
"""
if item.get('optional'):
# receipt has been marked as optional, so it doesn't matter
# if it's installed or not. Return 1
# only check receipts not marked as optional
munkicommon.display_debug1(
'Skipping %s because it is marked as optional',
item.get('packageid', item.get('name')))
return 1
if not INSTALLEDPKGS:
getInstalledPackages()
if 'packageid' in item and 'version' in item:
pkgid = item['packageid']
vers = item['version']
else:
raise munkicommon.Error('Missing packageid or version info!')
munkicommon.display_debug1('Looking for package %s, version %s',
pkgid, vers)
installedvers = INSTALLEDPKGS.get(pkgid)
if installedvers:
return compareVersions(installedvers, vers)
else:
munkicommon.display_debug1(
'\tThis package is not currently installed.')
return 0
def getInstalledVersion(item_plist):
"""Attempts to determine the currently installed version of an item.
Args:
item_plist: pkginfo plist of an item to get the version for.
Returns:
String version of the item, or 'UNKNOWN' if unable to determine.
"""
for receipt in item_plist.get('receipts', []):
# look for a receipt whose version matches the pkginfo version
if compareVersions(receipt.get('version', 0),
item_plist['version']) == 1:
pkgid = receipt['packageid']
munkicommon.display_debug2(
'Using receipt %s to determine installed version of %s',
pkgid, item_plist['name'])
return munkicommon.getInstalledPackageVersion(pkgid)
install_items_with_versions = [item
for item in item_plist.get('installs', [])
if 'CFBundleShortVersionString' in item]
for install_item in install_items_with_versions:
# look for an installs item whose version matches the pkginfo version
if compareVersions(install_item['CFBundleShortVersionString'],
item_plist['version']) == 1:
if install_item['type'] == 'application':
name = install_item.get('CFBundleName')
bundleid = install_item.get('CFBundleIdentifier')
munkicommon.display_debug2(
'Looking for application %s, bundleid %s',
name, install_item.get('CFBundleIdentifier'))
try:
# check default location for app
filepath = os.path.join(install_item['path'],
'Contents', 'Info.plist')
plist = FoundationPlist.readPlist(filepath)
return plist.get('CFBundleShortVersionString', 'UNKNOWN')
except FoundationPlist.NSPropertyListSerializationException:
# that didn't work, fall through to the slow way
appinfo = []
appdata = munkicommon.getAppData()
if appdata:
for ad_item in appdata:
if bundleid and ad_item['bundleid'] == bundleid:
appinfo.append(ad_item)
elif name and ad_item['name'] == name:
appinfo.append(ad_item)
maxversion = '0.0.0.0.0'
for ai_item in appinfo:
if 'version' in ai_item:
if compareVersions(ai_item['version'],
maxversion) == 2:
# version is higher
maxversion = ai_item['version']
return maxversion
elif install_item['type'] == 'bundle':
munkicommon.display_debug2(
'Using bundle %s to determine installed version of %s',
install_item['path'], item_plist['name'])
filepath = os.path.join(install_item['path'],
'Contents', 'Info.plist')
try:
plist = FoundationPlist.readPlist(filepath)
return plist.get('CFBundleShortVersionString', 'UNKNOWN')
except FoundationPlist.NSPropertyListSerializationException:
return "UNKNOWN"
elif install_item['type'] == 'plist':
munkicommon.display_debug2(
'Using plist %s to determine installed version of %s',
install_item['path'], item_plist['name'])
try:
plist = FoundationPlist.readPlist(install_item['path'])
return plist.get('CFBundleShortVersionString', 'UNKNOWN')
except FoundationPlist.NSPropertyListSerializationException:
return "UNKNOWN"
# if we fall through to here we have no idea what version we have
return 'UNKNOWN'
def download_installeritem(item_pl, installinfo, uninstalling=False):
"""Downloads an (un)installer item.
Returns True if the item was downloaded, False if it was already cached.
Raises an error if there are issues..."""
download_item_key = 'installer_item_location'
item_hash_key = 'installer_item_hash'
if uninstalling and 'uninstaller_item_location' in item_pl:
download_item_key = 'uninstaller_item_location'
item_hash_key = 'uninstaller_item_hash'
location = item_pl.get(download_item_key)
if not location:
raise fetch.MunkiDownloadError(
"No %s in item info.", download_item_key)
# allow pkginfo preferences to override system munki preferences
downloadbaseurl = item_pl.get('PackageCompleteURL') or \
item_pl.get('PackageURL') or \
munkicommon.pref('PackageURL') or \
munkicommon.pref('SoftwareRepoURL') + '/pkgs/'
# build a URL, quoting the the location to encode reserved characters
if item_pl.get('PackageCompleteURL'):
pkgurl = downloadbaseurl
else:
if not downloadbaseurl.endswith('/'):
downloadbaseurl = downloadbaseurl + '/'
pkgurl = downloadbaseurl + urllib2.quote(location)
pkgname = getInstallerItemBasename(location)
munkicommon.display_debug2('Download base URL is: %s', downloadbaseurl)
munkicommon.display_debug2('Package name is: %s', pkgname)
munkicommon.display_debug2('Download URL is: %s', pkgurl)
ManagedInstallDir = munkicommon.pref('ManagedInstallDir')
mycachedir = os.path.join(ManagedInstallDir, 'Cache')
destinationpath = getDownloadCachePath(mycachedir, location)
munkicommon.display_debug2('Downloading to: %s', destinationpath)
munkicommon.display_detail('Downloading %s from %s', pkgname, location)
if not os.path.exists(destinationpath):
# check to see if there is enough free space to download and install
if not enoughDiskSpace(item_pl, installinfo['managed_installs'],
uninstalling=uninstalling):
raise fetch.MunkiDownloadError(
'Insufficient disk space to download and install %s', pkgname)
else:
munkicommon.display_detail(
'Downloading %s from %s', pkgname, location)
dl_message = 'Downloading %s...' % pkgname
expected_hash = item_pl.get(item_hash_key, None)
try:
return getResourceIfChangedAtomically(pkgurl, destinationpath,
resume=True,
message=dl_message,
expected_hash=expected_hash,
verify=True)
except fetch.MunkiDownloadError:
raise
def isItemInInstallInfo(manifestitem_pl, thelist, vers=''):
"""Determines if an item is in a manifest plist.
Returns True if the manifest item has already
been processed (it's in the list) and, optionally,
the version is the same or greater.
"""
for item in thelist:
try:
if item['name'] == manifestitem_pl['name']:
if not vers:
return True
#if the version already installed or processed to be
#installed is the same or greater, then we're good.
if item.get('installed') and (compareVersions(
item.get('installed_version'), vers) in (1, 2)):
return True
if (compareVersions(
item.get('version_to_install'), vers) in (1, 2)):
return True
except KeyError:
# item is missing 'name', so doesn't match
pass
return False
def nameAndVersion(aString):
"""Splits a string into the name and version number.
Name and version must be seperated with a hyphen ('-')
or double hyphen ('--').
'TextWrangler-2.3b1' becomes ('TextWrangler', '2.3b1')
'AdobePhotoshopCS3--11.2.1' becomes ('AdobePhotoshopCS3', '11.2.1')
'MicrosoftOffice2008-12.2.1' becomes ('MicrosoftOffice2008', '12.2.1')
"""
for delim in ('--', '-'):
if aString.count(delim) > 0:
chunks = aString.split(delim)
vers = chunks.pop()
name = delim.join(chunks)
if vers[0] in '0123456789':
return (name, vers)
return (aString, '')
def getAllItemsWithName(name, cataloglist):
"""Searches the catalogs in a list for all items matching a given name.
Returns:
list of pkginfo items; sorted with newest version first. No precedence
is given to catalog order.
"""
def compare_item_versions(a, b):
"""Internal comparison function for use with sorting"""
return cmp(munkicommon.MunkiLooseVersion(b['version']),
munkicommon.MunkiLooseVersion(a['version']))
itemlist = []
# we'll throw away any included version info
name = nameAndVersion(name)[0]
munkicommon.display_debug1('Looking for all items matching: %s...', name)
for catalogname in cataloglist:
if not catalogname in CATALOG.keys():
# in case catalogname refers to a non-existent catalog...
continue
# is name in the catalog name table?
if name in CATALOG[catalogname]['named']:
versionsmatchingname = CATALOG[catalogname]['named'][name]
for vers in versionsmatchingname.keys():
if vers != 'latest':
indexlist = CATALOG[catalogname]['named'][name][vers]
for index in indexlist:
thisitem = CATALOG[catalogname]['items'][index]
if not thisitem in itemlist:
munkicommon.display_debug1(
'Adding item %s, version %s from catalog %s...',
name, thisitem['version'], catalogname)
itemlist.append(thisitem)
if itemlist:
# sort so latest version is first
itemlist.sort(compare_item_versions)
return itemlist
def trimVersionString(version_string):
"""Trims all lone trailing zeros in the version string after major/minor.
Examples:
10.0.0.0 -> 10.0
10.0.0.1 -> 10.0.0.1
10.0.0-abc1 -> 10.0.0-abc1
10.0.0-abc1.0 -> 10.0.0-abc1
"""
if version_string == None or version_string == '':
return ''
version_parts = version_string.split('.')
# strip off all trailing 0's in the version, while over 2 parts.
while len(version_parts) > 2 and version_parts[-1] == '0':
del version_parts[-1]
return '.'.join(version_parts)
def getItemDetail(name, cataloglist, vers=''):
"""Searches the catalogs in list for an item matching the given name.
If no version is supplied, but the version is appended to the name
('TextWrangler--2.3.0.0.0') that version is used.
If no version is given at all, the latest version is assumed.
Returns a pkginfo item.
"""
def compare_version_keys(a, b):
"""Internal comparison function for use in sorting"""
return cmp(munkicommon.MunkiLooseVersion(b),
munkicommon.MunkiLooseVersion(a))
if vers == 'apple_update_metadata':
vers = 'latest'
else:
(name, includedversion) = nameAndVersion(name)
if vers == '':
if includedversion:
vers = includedversion
if vers:
vers = trimVersionString(vers)
else:
vers = 'latest'
munkicommon.display_debug1(
'Looking for detail for: %s, version %s...', name, vers)
rejected_items = []
for catalogname in cataloglist:
if not catalogname in CATALOG.keys():
# in case the list refers to a non-existent catalog
continue
# is name in the catalog?
if name in CATALOG[catalogname]['named']:
itemsmatchingname = CATALOG[catalogname]['named'][name]
indexlist = []
if vers == 'latest':
# order all our items, latest first
versionlist = itemsmatchingname.keys()
versionlist.sort(compare_version_keys)
for versionkey in versionlist: