forked from munki/munki-pkg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
munkipkg
executable file
·1312 lines (1136 loc) · 48.6 KB
/
munkipkg
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/env python3
# encoding: utf-8
"""
munkipkg
A tool for making packages from projects that can be easily managed in a
version control system like git.
"""
# Copyright 2015-2022 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.
from __future__ import absolute_import, print_function
import glob
import json
import optparse
import os
import plistlib
import shutil
import stat
import subprocess
import sys
import tempfile
import time
from xml.dom import minidom
from xml.parsers.expat import ExpatError
try:
import yaml
YAML_INSTALLED = True
except ImportError:
YAML_INSTALLED = False
from xml.dom import minidom
from xml.parsers.expat import ExpatError
VERSION = "1.0"
DITTO = "/usr/bin/ditto"
LSBOM = "/usr/bin/lsbom"
PKGBUILD = "/usr/bin/pkgbuild"
PKGUTIL = "/usr/sbin/pkgutil"
PRODUCTBUILD = "/usr/bin/productbuild"
XCRUN = "/usr/bin/xcrun"
GITIGNORE_DEFAULT = """# .DS_Store files!
.DS_Store
# our build directory
build/
"""
BUILD_INFO_FILE = "build-info"
REQUIREMENTS_PLIST = "product-requirements.plist"
BOM_TEXT_FILE = "Bom.txt"
STAPLE_TIMEOUT = 300
STAPLE_SLEEP = 5
class MunkiPkgError(Exception):
'''Base Exception for errors in this domain'''
pass
class BuildError(MunkiPkgError):
'''Exception for build errors'''
pass
class PkgImportError(MunkiPkgError):
'''Exception for pkg import errors'''
pass
def readPlistFromString(data):
'''Wrapper for the differences between Python 2 and Python 3's plistlib'''
try:
return plistlib.loads(data)
except AttributeError:
# plistlib module doesn't have a load function (as in Python 2)
return plistlib.readPlistFromString(data)
def readPlist(filepath):
'''Wrapper for the differences between Python 2 and Python 3's plistlib'''
try:
with open(filepath, "rb") as fileobj:
return plistlib.load(fileobj)
except AttributeError:
# plistlib module doesn't have a load function (as in Python 2)
return plistlib.readPlist(filepath)
def writePlist(plist, filepath):
'''Wrapper for the differences between Python 2 and Python 3's plistlib'''
try:
with open(filepath, "wb") as fileobj:
plistlib.dump(plist, fileobj)
except AttributeError:
# plistlib module doesn't have a dump function (as in Python 2)
plistlib.writePlist(plist, filepath)
def unlink_if_possible(pathname):
'''Attempt to remove pathname but don't raise an execption if it fails'''
try:
os.unlink(pathname)
except OSError as err:
print("WARNING: could not remove %s: %s" % (pathname, err),
file=sys.stderr)
def display(message, quiet=False, toolname=None):
'''Print message to stdout unless quiet is True'''
if not quiet:
if not toolname:
toolname = os.path.basename(sys.argv[0])
print(("%s: %s" % (toolname, message)))
def run_subprocess(cmd):
'''Runs cmd with Popen'''
proc = subprocess.Popen(
cmd,
shell=False,
universal_newlines=True,
bufsize=1,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
proc_stdout, proc_stderr = proc.communicate()
retcode = proc.returncode
return (retcode, proc_stdout, proc_stderr)
def validate_build_info_keys(build_info, file_path):
'''Validates the data read from build_info.(plist|json|yaml|yml)'''
valid_values = {
'compression': ['legacy', 'latest'],
'ownership': ['recommended', 'preserve', 'preserve-other'],
'postinstall_action': ['none', 'logout', 'restart'],
'suppress_bundle_relocation': [True, False],
'distribution_style': [True, False],
'preserve_xattr': [True, False],
}
for key in valid_values:
if key in build_info:
if build_info[key] not in valid_values[key]:
print("ERROR: %s key '%s' has illegal value: %s"
% (file_path, key, repr(build_info[key])),
file=sys.stderr)
print('ERROR: Legal values are: %s' % valid_values[key],
file=sys.stderr)
return False
return True
def read_build_info(path):
'''Reads and validates data in the build_info'''
build_info = None
exception_list = (ExpatError, ValueError)
if YAML_INSTALLED:
exception_list = (ExpatError, ValueError, yaml.scanner.ScannerError)
try:
if path.endswith('.json'):
with open(path, 'r') as openfile:
build_info = json.load(openfile)
elif path.endswith(('.yaml', '.yml')):
with open(path, 'r') as openfile:
build_info = yaml.load(openfile, Loader=yaml.FullLoader)
elif path.endswith('.plist'):
build_info = readPlist(path)
except exception_list as err:
raise BuildError("%s is not a valid %s file: %s"
% (path, path.split('.')[-1], str(err)))
validate_build_info_keys(build_info, path)
if '${version}' in build_info['name']:
build_info['name'] = build_info['name'].replace(
'${version}',
str(build_info['version'])
)
return build_info
def make_component_property_list(build_info, options):
"""Use pkgbuild --analyze to build a component property list; then
turn off package relocation, Return path to the resulting plist."""
component_plist = os.path.join(build_info['tmpdir'], 'component.plist')
cmd = [PKGBUILD]
if options.quiet:
cmd.append('--quiet')
cmd.extend(["--analyze", "--root", build_info['payload'], component_plist])
try:
returncode = subprocess.call(cmd)
except OSError as err:
raise BuildError(
"pkgbuild execution failed with error code %d: %s"
% (err.errno, err.strerror))
if returncode:
raise BuildError("pkgbuild failed with exit code %d" % returncode)
try:
plist = readPlist(component_plist)
except ExpatError as err:
raise BuildError("Couldn't read %s" % component_plist)
# plist is an array of dicts, iterate through
for bundle in plist:
if bundle.get("BundleIsRelocatable"):
bundle["BundleIsRelocatable"] = False
display('Turning off bundle relocation for %s'
% bundle['RootRelativeBundlePath'], options.quiet)
try:
writePlist(plist, component_plist)
except BaseException as err:
raise BuildError("Couldn't write %s" % component_plist)
return component_plist
def make_pkginfo(build_info, options):
'''Creates a stub PackageInfo file for use with pkgbuild'''
if build_info['postinstall_action'] != 'none' and not options.quiet:
display("Setting postinstall-action to %s"
% build_info['postinstall_action'], options.quiet)
pkginfo_path = os.path.join(build_info['tmpdir'], 'PackageInfo')
pkginfo_text = (
'<?xml version="1.0" encoding="utf-8" standalone="no"?>'
'<pkg-info postinstall-action="%s" preserve-xattr="%s"/>'
% (build_info['postinstall_action'],
str(build_info['preserve_xattr']).lower())
)
try:
fileobj = open(pkginfo_path, mode='w')
fileobj.write(pkginfo_text)
fileobj.close()
return pkginfo_path
except (OSError, IOError) as err:
raise BuildError('Couldn\'t create PackageInfo file: %s' % err)
def default_build_info(project_dir):
'''Return dict with default build info values'''
info = {}
info['ownership'] = "recommended"
info['suppress_bundle_relocation'] = True
info['postinstall_action'] = 'none'
info['preserve_xattr'] = False
basename = os.path.basename(project_dir.rstrip('/')).replace(" ", "")
info['name'] = basename + '-${version}.pkg'
info['identifier'] = "com.github.munki.pkg." + basename
info['install_location'] = '/'
info['version'] = "1.0"
info['distribution_style'] = False
return info
def get_build_info(project_dir, options):
'''Return dict with build info'''
info = default_build_info(project_dir)
info['project_dir'] = project_dir
# override default values with values from BUILD_INFO_PLIST
supported_keys = [
'compression',
'name',
'identifier',
'version',
'ownership',
'install_location',
'min-os-version',
'postinstall_action',
'preserve_xattr',
'suppress_bundle_relocation',
'distribution_style',
'signing_info',
'notarization_info',
]
build_file = os.path.join(project_dir, BUILD_INFO_FILE)
file_type = None
if not options.yaml and not options.json:
file_types = ['plist', 'json', 'yaml', 'yml']
for ext in file_types:
if os.path.exists(build_file + '.' + ext):
if file_type is None:
file_type = ext
else:
raise MunkiPkgError(
"ERROR: Multiple build-info files found!")
else:
file_type = (
'yaml' if options.yaml else 'json' if options.json else 'plist')
file_info = None
if file_type and os.path.exists(build_file + '.' + file_type):
file_info = read_build_info(build_file + '.' + file_type)
if file_info:
for key in supported_keys:
if key in file_info:
info[key] = file_info[key]
else:
raise MunkiPkgError('ERROR: No build-info file found!')
return info
def non_recommended_permissions_in_bom(project_dir):
'''Analyzes Bom.txt to determine if there are any items with owner/group
other than 0/0, which implies we should handle ownership differently'''
bom_list_file = os.path.join(project_dir, BOM_TEXT_FILE)
if not os.path.exists(bom_list_file):
return False
try:
with open(bom_list_file) as fileref:
while True:
item = fileref.readline()
if not item:
break
if item == '\n':
# shouldn't be any empty lines in Bom.txt, but...
continue
parts = item.rstrip('\n').split('\t')
user_group = parts[2]
if user_group != '0/0':
return True
return False
except (OSError, ValueError) as err:
print('ERROR: %s' % err, file=sys.stderr)
return False
def sync_from_bom_info(project_dir, options):
'''Uses Bom.txt to apply modes to files in payload dir and create any
missing empty directories, since git does not track these.'''
# possible to-do: preflight check: if there are files missing
# (and not just directories), or there are extra files or directories,
# bail without making any changes
# possible to-do: a refinement of the above preflight check
# -- also check file checksums
bom_list_file = os.path.join(project_dir, BOM_TEXT_FILE)
payload_dir = os.path.join(project_dir, 'payload')
try:
build_info = get_build_info(project_dir, options)
except MunkiPkgError:
build_info = default_build_info(project_dir)
running_as_root = (os.geteuid() == 0)
if not os.path.exists(bom_list_file):
print((
"ERROR: Can't sync with bom info: no %s found in project directory."
% BOM_TEXT_FILE), file=sys.stderr)
return -1
if build_info['ownership'] != 'recommended' and not running_as_root:
print((
"\nWARNING: build-info ownership: %s might require using "
"sudo to properly sync owner and group for payload files.\n"
% build_info['ownership']), file=sys.stderr)
returncode = 0
changes_made = 0
try:
with open(bom_list_file) as fileref:
while True:
item = fileref.readline()
if not item:
break
if item == '\n':
# shouldn't be any empty lines in Bom.txt, but...
continue
parts = item.rstrip('\n').split('\t')
path = parts[0]
if path.startswith('./'):
path = path[2:]
full_mode = parts[1]
user_group = parts[2].partition('/')
desired_user = int(user_group[0])
desired_group = int(user_group[2])
desired_mode = int(full_mode[-4:], 8)
payload_path = os.path.join(payload_dir, path)
basename = os.path.basename(path)
if basename.startswith('._'):
otherfile = os.path.join(
os.path.dirname(path), basename[2:])
print((
'WARNING: file %s contains extended attributes or a '
'resource fork for %s. git and pkgbuild may not '
'properly preserve extended attributes.'
% (path, otherfile)), file=sys.stderr)
continue
if os.path.lexists(payload_path):
# file exists, check permission bits and adjust if needed
current_mode = stat.S_IMODE(os.lstat(payload_path).st_mode)
if current_mode != desired_mode:
display("Changing mode of %s to %s"
% (payload_path, oct(desired_mode)),
options.quiet)
os.lchmod(payload_path, desired_mode)
changes_made += 1
elif full_mode.startswith('4'):
# file doesn't exist and it's a directory; re-create it
display("Creating %s with mode %s"
% (payload_path, oct(desired_mode)),
options.quiet)
os.mkdir(payload_path, desired_mode)
changes_made += 1
continue
else:
# missing file. This is a problem.
print("ERROR: File %s is missing in payload"
% payload_path, file=sys.stderr)
returncode = -1
break
if running_as_root:
# we can sync owner and group as well
current_user = os.lstat(payload_path).st_uid
current_group = os.lstat(payload_path).st_gid
if (current_user != desired_user or
current_group != desired_group):
display("Changing user/group of %s to %s/%s"
% (payload_path, desired_user, desired_group),
options.quiet)
os.lchown(payload_path, desired_user, desired_group)
changes_made += 1
except (OSError, ValueError) as err:
print('ERROR: %s' % err, file=sys.stderr)
return -1
if returncode == 0 and not options.quiet:
if changes_made:
display("Sync successful.")
else:
display("Sync successful: no changes needed.")
return returncode
def add_project_subdirs(build_info):
'''Adds and validates project subdirs to build_info'''
# validate payload and scripts dirs
project_dir = build_info['project_dir']
payload_dir = os.path.join(project_dir, 'payload')
scripts_dir = os.path.join(project_dir, 'scripts')
if not os.path.isdir(payload_dir):
payload_dir = None
if not os.path.isdir(scripts_dir):
scripts_dir = None
elif os.listdir(scripts_dir) in [[], ['.DS_Store']]:
# scripts dir is empty; don't include it as part of build
scripts_dir = None
if not payload_dir and not scripts_dir:
raise BuildError(
"%s does not contain a payload folder or a scripts folder."
% project_dir)
# make sure build directory exists
build_dir = os.path.join(project_dir, 'build')
if not os.path.exists(build_dir):
os.mkdir(build_dir)
elif not os.path.isdir(build_dir):
raise BuildError("%s is not a directory." % build_dir)
build_info['payload'] = payload_dir
build_info['scripts'] = scripts_dir
build_info['build_dir'] = build_dir
build_info['tmpdir'] = tempfile.mkdtemp()
def write_build_info(build_info, project_dir, options):
'''writes out our build-info file in preferred format'''
try:
if options.json:
build_info_json = os.path.join(
project_dir, "%s.json" % BUILD_INFO_FILE)
with open(build_info_json, 'w') as json_file:
json.dump(
build_info, json_file, ensure_ascii=True,
indent=4, separators=(',', ': '))
elif options.yaml:
build_info_yaml = os.path.join(
project_dir, "%s.yaml" % BUILD_INFO_FILE)
with open(build_info_yaml, 'w') as yaml_file:
yaml_file.write(
yaml.dump(build_info, default_flow_style=False)
)
else:
build_info_plist = os.path.join(
project_dir, "%s.plist" % BUILD_INFO_FILE)
writePlist(build_info, build_info_plist)
except OSError as err:
raise MunkiPkgError(err)
def create_default_gitignore(project_dir):
'''Create default .gitignore file for new projects'''
gitignore_file = os.path.join(project_dir, '.gitignore')
fileobj = open(gitignore_file, "w")
fileobj.write(GITIGNORE_DEFAULT)
fileobj.close()
def create_template_project(project_dir, options):
'''Create an empty pkg project directory with default settings'''
if os.path.exists(project_dir):
if not options.force:
print((
"ERROR: %s already exists! "
"Use --force to convert it to a project directory."
% project_dir), file=sys.stderr)
return -1
payload_dir = os.path.join(project_dir, 'payload')
scripts_dir = os.path.join(project_dir, 'scripts')
build_dir = os.path.join(project_dir, 'build')
try:
if not os.path.exists(project_dir):
os.mkdir(project_dir)
os.mkdir(payload_dir)
os.mkdir(scripts_dir)
os.mkdir(build_dir)
build_info = default_build_info(project_dir)
write_build_info(build_info, project_dir, options)
create_default_gitignore(project_dir)
display(
"Created new package project at %s" % project_dir, options.quiet)
except (OSError, MunkiPkgError) as err:
print('ERROR: %s' % err, file=sys.stderr)
return -1
return 0
def export_bom(bomfile, project_dir):
'''Exports bom to text format. Returns returncode from lsbom'''
destination = os.path.join(project_dir, BOM_TEXT_FILE)
try:
with open(destination, mode='w') as fileobj:
cmd = [LSBOM, bomfile]
proc = subprocess.Popen(cmd, stdout=fileobj, stderr=subprocess.PIPE)
_, stderr = proc.communicate()
if proc.returncode:
raise MunkiPkgError(stderr)
except OSError as err:
raise MunkiPkgError(err)
def export_bom_info(build_info, options):
'''Extract the bom file from the built package and export its info to the
project directory'''
pkg_path = os.path.join(build_info['build_dir'], build_info['name'])
cmd = [PKGUTIL, '--bom', pkg_path]
display("Extracting bom file from %s" % pkg_path, options.quiet)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
if proc.returncode:
raise BuildError(stderr.strip())
bomfile = stdout.strip()
destination = os.path.join(build_info['project_dir'], BOM_TEXT_FILE)
display("Exporting bom info to %s" % destination, options.quiet)
export_bom(bomfile, build_info['project_dir'])
unlink_if_possible(bomfile)
def add_signing_options_to_cmd(cmd, build_info, options):
'''If build_info contains signing options, add them to the cmd'''
if 'signing_info' in build_info:
display("Adding package signing info to command", options.quiet)
signing_info = build_info['signing_info']
if 'identity' in signing_info:
cmd.extend(['--sign', signing_info['identity']])
else:
raise BuildError('Missing identity in signing info!')
if 'keychain' in signing_info:
cmd.extend(['--keychain', signing_info['keychain']])
if 'additional_cert_names' in signing_info:
additional_cert_names = signing_info['additional_cert_names']
# convert single string to list
try:
text_types = basestring # pylint: disable=basestring-builtin
except NameError:
text_types = str
if isinstance(additional_cert_names, text_types):
additional_cert_names = [additional_cert_names]
for cert_name in additional_cert_names:
cmd.extend(['--cert', cert_name])
if 'timestamp' in signing_info:
if signing_info['timestamp']:
cmd.extend(['--timestamp'])
else:
cmd.extend(['--timestamp=none'])
def build_pkg(build_info, options):
'''Use pkgbuild tool to build our package'''
cmd = [PKGBUILD,
'--ownership', build_info['ownership'],
'--identifier', build_info['identifier'],
'--version', str(build_info['version']),
'--info', build_info['pkginfo_path']]
if build_info['payload']:
cmd.extend(['--root', build_info['payload']])
if build_info.get('install_location'):
cmd.extend(['--install-location', build_info['install_location']])
else:
cmd.extend(['--nopayload'])
if 'compression' in build_info:
cmd.extend(['--compression', build_info['compression']])
if build_info['component_plist']:
cmd.extend(['--component-plist', build_info['component_plist']])
if 'min-os-version' in build_info:
cmd.extend(['--min-os-version', build_info['min-os-version']])
if build_info['scripts']:
cmd.extend(['--scripts', build_info['scripts']])
if options.quiet:
cmd.append('--quiet')
if not build_info.get('distribution_style'):
add_signing_options_to_cmd(cmd, build_info, options)
cmd.append(os.path.join(build_info['build_dir'], build_info['name']))
retcode = subprocess.call(cmd)
if retcode:
raise BuildError("Package creation failed.")
def build_distribution_pkg(build_info, options):
'''Converts component pkg to dist pkg'''
pkginputname = os.path.join(build_info['build_dir'], build_info['name'])
distoutputname = os.path.join(
build_info['build_dir'], 'Dist-' + build_info['name'])
if os.path.exists(distoutputname):
retcode = subprocess.call(["/bin/rm", "-rf", distoutputname])
if retcode:
raise BuildError(
'Error removing existing %s: %s' % (distoutputname, retcode))
cmd = [PRODUCTBUILD]
if options.quiet:
cmd.append('--quiet')
add_signing_options_to_cmd(cmd, build_info, options)
# if there is a PRE-INSTALL REQUIREMENTS PROPERTY LIST, use it
requirements_plist = os.path.join(
build_info['project_dir'], REQUIREMENTS_PLIST)
if os.path.exists(requirements_plist):
cmd.extend(['--product', requirements_plist])
# if build_info contains a product id use that for product id, otherwise
# use package identifier
product_id = build_info.get('product id', build_info['identifier'])
cmd.extend(['--identifier', product_id, '--version', str(build_info['version'])])
# add the input and output package paths
cmd.extend(['--package', pkginputname, distoutputname])
retcode = subprocess.call(cmd)
if retcode:
raise BuildError("Distribution package creation failed.")
try:
display("Removing component package %s" % pkginputname, options.quiet)
os.unlink(pkginputname)
display("Renaming distribution package %s to %s"
% (distoutputname, pkginputname), options.quiet)
os.rename(distoutputname, pkginputname)
except OSError as err:
raise BuildError(err)
def get_primary_bundle_id(build_info):
'''Gets primary bundle id for notarization'''
primary_bundle_id = build_info['notarization_info'].get(
'primary_bundle_id',
build_info['identifier'],
)
# Apple notary service does not like underscores
primary_bundle_id = primary_bundle_id.replace('_', '-')
return primary_bundle_id
def add_authentication_options(cmd, build_info):
'''Add --password or --apiKey + --apiIssuer options to the command'''
if (
'apple_id' in build_info['notarization_info'] and
'team_id' in build_info['notarization_info'] and
'password' in build_info['notarization_info']
):
cmd.extend(
[
'--apple-id', build_info['notarization_info']['apple_id'],
'--team-id', build_info['notarization_info']['team_id'],
'--password', build_info['notarization_info']['password']
]
)
elif (
'keychain_profile' in build_info['notarization_info']
):
cmd.extend(
[
'--keychain-profile',
build_info['notarization_info']['keychain_profile']
]
)
else:
raise MunkiPkgError(
"apple_id + team_id + password or keychain_profile "
"must be specified in notarization_info."
)
def upload_to_notary(build_info, options):
'''Use xcrun notarytool to upload the package to Apple notary service'''
display("Uploading package to Apple notary service", options.quiet)
cmd = [
XCRUN,
'notarytool',
'submit',
'--output-format',
'plist',
os.path.join(build_info['build_dir'], build_info['name']),
]
add_authentication_options(cmd, build_info)
retcode, proc_stdout, proc_stderr = run_subprocess(cmd)
if retcode:
print("notarytool: " + proc_stderr, file=sys.stderr)
raise MunkiPkgError("Notarization upload failed.")
if proc_stdout.startswith('Generated JWT'):
proc_stdout = proc_stdout.split('\n',1)[1]
try:
output = readPlistFromString(proc_stdout.encode("UTF-8"))
except ExpatError:
print("notarytool: " + proc_stderr, file=sys.stderr)
raise MunkiPkgError("Notarization upload failed.")
try:
request_id = output['id']
display("id " + request_id, options.quiet, "notarytool")
display(output['message'], options.quiet, "notarytool")
except KeyError:
raise MunkiPkgError("Unexpected output from notarytool")
return request_id
def get_notarization_state(request_id, build_info, options):
'''Checks for result of notarization process'''
state = {}
cmd = [
XCRUN,
'notarytool',
'info',
request_id,
'--output-format',
'plist',
]
add_authentication_options(cmd, build_info)
retcode, proc_stdout, proc_stderr = run_subprocess(cmd)
if retcode:
print("notarytool: " + proc_stderr, file=sys.stderr)
raise MunkiPkgError("Notarization check failed.")
if proc_stdout.startswith('Generated JWT'):
proc_stdout = proc_stdout.split('\n',1)[1]
try:
output = readPlistFromString(proc_stdout.encode("UTF-8"))
except ExpatError:
print(proc_stderr, file=sys.stderr)
raise MunkiPkgError("Notarization check failed.")
if 'message' not in output:
print("notarytool: " + output.get('success-message', 'Unexpected response'))
print("notarytool: DEBUG output follows")
print(output)
state['status'] = 'Unknown'
else:
state['id'] = output.get('id', '')
state['status'] = output.get('status', 'Unknown')
state['message'] = output.get('message', '')
return state
def notarization_done(state, sleep_time, options):
'''Evaluates whether notarization is still in progress'''
if state['status'] == 'Accepted':
display("Notarization successful. {}".format(state['message']), options.quiet)
return True
elif state['status'] in ['In Progress', 'Unknown']:
display(
"Notarization state: {}. Trying again in {} seconds".format(
state['status'],
sleep_time,
),
options.quiet,
)
return False
else:
display(
"Notarization unsuccessful:\n"
"\tStatus(id={}): {}\n"
"\tStatus Message: {}".format(
state['id'], state['status'], state['message']
),
options.quiet,
)
raise MunkiPkgError("Notarization failed")
def wait_for_notarization(request_id, build_info, options):
'''Checks notarization state until it is done or we exceed the timeout value'''
display("Getting notarization state", options.quiet)
timeout = build_info['notarization_info'].get('staple_timeout', STAPLE_TIMEOUT)
counter = 0
sleep_time = STAPLE_SLEEP
while counter < timeout:
time.sleep(sleep_time)
counter += sleep_time
sleep_time += STAPLE_SLEEP
state = get_notarization_state(request_id, build_info, options)
if notarization_done(state, sleep_time, options):
return True
print(
"munkipkg: Timeout EXCEEDED when waiting for the notarization to complete. "
"You can manually staple the package later if notarization is successful.",
file=sys.stderr,
)
return False
def staple(build_info, options):
'''Use xcrun staple to add a staple to our package'''
display("Stapling package", options.quiet)
cmd = [
XCRUN,
'stapler',
'staple',
os.path.join(build_info['build_dir'], build_info['name']),
]
retcode, proc_stdout, proc_stderr = run_subprocess(cmd)
if retcode:
print("stapler: FAILURE " + proc_stderr, file=sys.stderr)
raise MunkiPkgError("Stapling failed")
else:
display("The staple and validate action worked!", options.quiet)
def build(project_dir, options):
'''Build our package'''
build_info = {}
try:
try:
build_info = get_build_info(project_dir, options)
except MunkiPkgError as err:
print(str(err), file=sys.stderr)
exit(-1)
if build_info['ownership'] in ['preserve', 'preserve-other']:
if os.geteuid() != 0:
print("\nWARNING: build-info ownership: %s might require "
"using sudo to build this package.\n"
% build_info['ownership'], file=sys.stderr)
add_project_subdirs(build_info)
build_info['component_plist'] = None
# analyze root and turn off bundle relocation
if build_info['payload'] and build_info['suppress_bundle_relocation']:
build_info['component_plist'] = make_component_property_list(
build_info, options)
# make a stub PkgInfo file
build_info['pkginfo_path'] = make_pkginfo(build_info, options)
# remove any pre-existing pkg at the outputname path
outputname = os.path.join(build_info['build_dir'], build_info['name'])
if os.path.exists(outputname):
retcode = subprocess.call(["/bin/rm", "-rf", outputname])
if retcode:
raise BuildError("Could not remove existing %s" % outputname)
if build_info['scripts']:
# remove .DS_Store file from the scripts folder
if os.path.exists(os.path.join(build_info['scripts'], ".DS_Store")):
display("Removing .DS_Store file from the scripts folder",
options.quiet)
os.remove(os.path.join(build_info['scripts'], ".DS_Store"))
# make scripts executable
for pkgscript in ("preinstall", "postinstall"):
scriptpath = os.path.join(build_info['scripts'], pkgscript)
if (os.path.exists(scriptpath) and
(os.stat(scriptpath).st_mode & 0o500) != 0o500):
display("Making %s script executable" % pkgscript,
options.quiet)
os.chmod(scriptpath, 0o755)
# build the pkg
build_pkg(build_info, options)
# export bom info if requested
if options.export_bom_info:
export_bom_info(build_info, options)
# convert pkg to distribution-style if requested
if build_info['distribution_style']:
build_distribution_pkg(build_info, options)
# notarize the pkg
if 'notarization_info' in build_info and not options.skip_notarization:
try:
request_id = upload_to_notary(build_info, options)
if not options.skip_stapling and wait_for_notarization(
request_id, build_info, options
):
staple(build_info, options)
except MunkiPkgError as err:
print("ERROR: %s" % err, file=sys.stderr)
return -1
# cleanup temp dir
_ = subprocess.call(["/bin/rm", "-rf", build_info['tmpdir']])
return 0
except BuildError as err:
print('ERROR: %s' % err, file=sys.stderr)
if build_info.get('tmpdir'):
# cleanup temp dir
_ = subprocess.call(["/bin/rm", "-rf", build_info['tmpdir']])
return -1
def get_pkginfo_attr(pkginfo_dom, attribute_name):
"""Returns value for attribute_name from PackageInfo dom"""
pkgrefs = pkginfo_dom.getElementsByTagName('pkg-info')
if pkgrefs:
for ref in pkgrefs:
keys = list(ref.attributes.keys())
if attribute_name in keys:
return ref.attributes[attribute_name].value
return None
def expand_payload(project_dir):
'''expand Payload if present'''
payload_file = os.path.join(project_dir, 'Payload')
payload_archive = os.path.join(project_dir, 'Payload.cpio.gz')
payload_dir = os.path.join(project_dir, 'payload')
if os.path.exists(payload_file):
try:
os.rename(payload_file, payload_archive)
os.mkdir(payload_dir)
except OSError as err:
raise PkgImportError(err)
cmd = [DITTO, '-x', payload_archive, payload_dir]
retcode = subprocess.call(cmd)
if retcode:
raise PkgImportError("Ditto failed to expand Payload")
unlink_if_possible(payload_archive)
def convert_packageinfo(pkg_path, project_dir, options):
'''parse PackageInfo file and create build-info file'''
package_info_file = os.path.join(project_dir, 'PackageInfo')
pkginfo = minidom.parse(package_info_file)
build_info = {}
build_info['identifier'] = get_pkginfo_attr(pkginfo, 'identifier') or ''
build_info['version'] = get_pkginfo_attr(pkginfo, 'version') or '1.0'
build_info['install_location'] = get_pkginfo_attr(
pkginfo, 'install-location') or '/'
build_info['postinstall_action'] = get_pkginfo_attr(
pkginfo, 'postinstall-action') or 'none'
build_info['preserve_xattr'] = get_pkginfo_attr(
pkginfo, 'preserve-xattr') == "true"
build_info['name'] = os.path.basename(pkg_path)
if non_recommended_permissions_in_bom(project_dir):
build_info['ownership'] = 'preserve'
distribution_file = os.path.join(project_dir, 'Distribution')
build_info['distribution_style'] = os.path.exists(distribution_file)