forked from tranquilit/WAPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaptpackage.py
3508 lines (2880 loc) · 137 KB
/
waptpackage.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
#!/opt/wapt/bin/python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------
# This file is part of WAPT
# Copyright (C) 2013 Tranquil IT Systems http://www.tranquil.it
# WAPT aims to help Windows systems administrators to deploy
# setup and update applications on users PC.
#
# WAPT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# WAPT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WAPT. If not, see <http://www.gnu.org/licenses/>.
#
# -----------------------------------------------------------------------
from __future__ import absolute_import
from waptutils import __version__
__all__ = [
'control_to_dict',
'md5_for_file',
'parse_major_minor_patch_build',
'make_version',
'PackageVersion',
'PackageRequest',
'PackageEntry',
'HostCapabilities',
'WaptBaseRepo',
'WaptLocalRepo',
'WaptRemoteRepo',
'update_packages',
'REGEX_PACKAGE_VERSION',
'REGEX_PACKAGE_CONDITION',
'ArchitecturesList',
'EWaptException',
'EWaptBadSignature',
'EWaptCorruptedFiles',
'EWaptNotSigned',
'EWaptBadControl',
'EWaptBadSetup',
'EWaptNeedsNewerAgent',
'EWaptDiskSpace',
'EWaptBadTargetOS',
'EWaptNotAPackage',
'EWaptDownloadError',
'EWaptMissingLocalWaptFile',
'EWaptNeedsNewerAgent',
'EWaptConfigurationError',
'EWaptUnavailablePackage',
'EWaptNotSourcesDirPackage',
'EWaptPackageSignError',
'EWaptConflictingPackage',
'EWaptInstallPostponed',
'EWaptInstallError',
]
import os
import custom_zip as zipfile
import StringIO
import hashlib
import logging
import glob
import codecs
import re
import time
import json
import ujson
import sys
import types
import requests
import email
import datetime
import tempfile
import email.utils
import shutil
import base64
import copy
import gc
import uuid
from iniparse import RawConfigParser
import traceback
from waptutils import BaseObjectClass,Version,ensure_unicode,ZipFile,force_utf8_no_bom
from waptutils import create_recursive_zip,ensure_list,all_files,list_intersection
from waptutils import datetime2isodate,httpdatetime2isodate,httpdatetime2datetime,fileutcdate,fileisoutcdate,isodate2datetime
from waptutils import default_http_headers,wget,get_language,import_setup,import_code
from waptutils import _disable_file_system_redirection
from waptutils import get_requests_client_cert_session
from waptcrypto import EWaptMissingCertificate,EWaptBadCertificate
from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey,SSLCRL
from waptcrypto import SSLVerifyException,hexdigest_for_data,hexdigest_for_file,serialize_content_for_signature
from waptcrypto import is_pem_key_encrypted
logger = logging.getLogger()
def md5_for_file(fname, block_size=2**20):
"""Calculate the md5 hash of file.
Returns:
str: md5 hash as hexadecimal string.
"""
f = open(fname,'rb')
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.hexdigest()
# From Semantic Versioning : http://semver.org/ by Tom Preston-Werner,
# valid : 0.0-0 0.0.0-0 0.0.0.0-0
REGEX_PACKAGE_VERSION = re.compile(r'^(?P<major>[0-9]+)'
'(\.(?P<minor>[0-9]+))?'
'(\.(?P<patch>[0-9]+))?'
'(\.(?P<subpatch>[0-9]+))?'
'(\-(?P<packaging>[0-9A-Za-z]+(\.[0-9A-Za-z]+)*))?$')
# tis-exodus(>2.3.4-10)
# changed in 1.6.2.4
REGEX_PACKAGE_CONDITION = re.compile(r'(?P<package>[^()]+)\s*(\(\s*(?P<operator>[<=>]*)\s*(?P<version>\S+)\s*\))?')
REGEX_VERSION_CONDITION = re.compile(r'(?P<operator>[<=>]*)\s*(?P<version>\S+)')
def parse_major_minor_patch_build(version):
"""Parse version to major, minor, patch, pre-release, build parts.
"""
match = REGEX_PACKAGE_VERSION.match(version)
if match is None:
raise ValueError(u'%s is not valid SemVer string' % version)
verinfo = match.groupdict()
def int_or_none(name):
if name in verinfo and verinfo[name] != None :
return int(verinfo[name])
else:
return None
verinfo['major'] = int_or_none('major')
verinfo['minor'] = int_or_none('minor')
verinfo['patch'] = int_or_none('patch')
verinfo['subpatch'] = int_or_none('subpatch')
return verinfo
def make_version(major_minor_patch_build):
p1 = u'.'.join( [ "%s" % major_minor_patch_build[p] for p in ('major','minor','patch','subpatch') if major_minor_patch_build[p] != None])
if major_minor_patch_build['packaging'] != None:
return '-'.join([p1,major_minor_patch_build['packaging']])
else:
return p1
ArchitecturesList = ('all','x86','x64')
class EWaptException(Exception):
pass
class EWaptBadSignature(EWaptException):
pass
class EWaptDownloadError(EWaptException):
pass
class EWaptCorruptedFiles(EWaptException):
pass
class EWaptNotSigned(EWaptException):
pass
class EWaptBadControl(EWaptException):
pass
class EWaptBadSetup(EWaptException):
pass
class EWaptNeedsNewerAgent(EWaptException):
pass
class EWaptDiskSpace(EWaptException):
pass
class EWaptBadTargetOS(EWaptException):
pass
class EWaptNotAPackage(EWaptException):
pass
class EWaptNotSourcesDirPackage(EWaptException):
pass
class EWaptMissingPackageHook(EWaptException):
pass
class EWaptPackageSignError(EWaptException):
pass
class EWaptInstallError(EWaptException):
"""Exception raised during installation of package
msg is logged in local install database
if retry_count is None, install will be retried indefinitely until success
else install is retried at most retry_count times.
"""
def __init__(self,msg,install_status='ERROR',retry_count=None):
Exception.__init__(self,msg)
self.install_status = install_status
self.retry_count = retry_count
class EWaptInstallPostponed(EWaptInstallError):
def __init__(self,msg,install_status='POSTPONED',retry_count=5,grace_delay=3600):
EWaptInstallError.__init__(self,msg,install_status,retry_count)
self.grace_delay = grace_delay
class EWaptUnavailablePackage(EWaptInstallError):
pass
class EWaptConflictingPackage(EWaptInstallError):
pass
class EWaptRemoveError(EWaptException):
pass
class EWaptConfigurationError(EWaptException):
pass
class EWaptMissingLocalWaptFile(EWaptException):
pass
class HostCapabilities(BaseObjectClass):
__all_attributes = ['uuid', 'language', 'os', 'os_version', 'architecture', 'dn', 'fqdn',
'site', 'wapt_version', 'wapt_edition', 'packages_trusted_ca_fingerprints',
'packages_blacklist', 'packages_whitelist', 'packages_locales',
'packages_maturities', 'use_host_packages','host_packages_names',
'host_profiles', 'host_certificate_fingerprint','host_certificate_authority_key_identifier']
def __init__(self,**kwargs):
self.uuid = None
self.language = None
self.os = None
self.os_version = None
self.architecture = None
self.dn = None
self.fqdn = None
self.site = None
self.wapt_version = None
self.wapt_edition = None
self.packages_trusted_ca_fingerprints = None
self.packages_blacklist = None
self.packages_whitelist = None
self.packages_locales = None
self.packages_maturities = None
self.use_host_packages = None
self.host_profiles = None
self.host_packages_names = None
self.host_certificate_fingerprint = None
self.host_certificate_authority_key_identifier = None
for (k,v) in kwargs.iteritems():
if hasattr(self,k):
setattr(self,k,v)
else:
#raise Exception('HostCapabilities has no attribute %s' % k)
logger.critical('HostCapabilities has no attribute %s : ignored' % k)
def __getitem__(self,name):
if name is str or name is unicode:
name = name.lower()
if hasattr(self,name):
return getattr(self,name)
else:
raise Exception(u'%s : No such attribute : %s' % (self.__class__.__name__,name))
def __iter__(self):
for key in self.__all_attributes:
yield (key, getattr(self,key))
def as_dict(self):
return dict(self)
def fingerprint(self):
return hashlib.sha256(serialize_content_for_signature(self.as_dict())).hexdigest()
def get_package_request_filter(self):
"""Returns a filter for package search in repositories
Returns:
PackageRequest
"""
return PackageRequest(
architectures=ensure_list(self.architecture),
locales=ensure_list(self.packages_locales),
maturities=self.packages_maturities,
min_os_version=self.os_version,
max_os_version=self.os_version,
)
def is_matching_package(self,package_entry):
"""Check if package_entry is matching the current capabilities and restrictions
"""
if self.packages_blacklist is not None:
for bl in self.packages_blacklist: # pylint: disable=not-an-iterable
if glob.fnmatch.fnmatch(package_entry.package,bl):
return False
if self.packages_whitelist is not None:
allowed = False
for wl in self.packages_whitelist: # pylint: disable=not-an-iterable
if glob.fnmatch.fnmatch(package_entry.package,wl):
allowed = True
break
if not allowed:
return False
if self.wapt_version is not None and package_entry.min_wapt_version and Version(package_entry.min_wapt_version) > Version(self.wapt_version):
return False
if self.os is not None and package_entry.target_os and package_entry.target_os != self.os:
return False
package_request = self.get_package_request_filter()
return package_request.is_matched_by(package_entry)
def __repr__(self):
return repr(self.as_dict())
class PackageKey(object):
def __init__(self,package_uuid=None,package=None,version=None,architecture=None,locale=None,maturity=None,**kwargs):
self.package_uuid=package_uuid
self.package = package
self.version = version
self.architecture = architecture
self.locale = locale
self.maturity = maturity
for k,v in kwargs:
if hasattr(self,k):
setattr(self,k,v)
def __unicode__(self):
def and_list(v):
if isinstance(v,list) or isinstance(v,tuple):
return u','.join(ensure_list(v))
else:
return v
attribs=[]
attribs.extend([u"%s" % (ensure_unicode(and_list(getattr(self,a)))) for a in ['architecture','locale','maturity']
if getattr(self,a) is not None and getattr(self,a) != '' and getattr(self,a) != 'all'])
if attribs:
attribs = u' [%s]' % u'_'.join(attribs)
else:
attribs = u''
return "%s (=%s)%s" % (self.package,self.version,attribs)
def __str__(self):
return "%s" % self.__unicode__()
def __iter__(self):
return iter((self.package,self.version,self.architecture,self.locale,self.maturity))
def as_dict(self):
return dict(
package=self.package,
version=self.version,
architecture=self.architecture,
locale=self.locale,
maturity=self.maturity,
)
def __repr__(self):
return repr(self.as_dict())
def __cmp__(self,other):
if self.package_uuid and other.package_uuid and self.package_uuid == other.package_uuid:
return 0
return cmp((self.package,self.version,self.architecture,self.locale,self.maturity),(other.package,other.version,other.architecture,other.locale,other.maturity))
def PackageVersion(package_or_versionstr):
"""Splits a version string 1.2.3.4-567
software version is clipped to 4 members
if '-packaging' is not provided, the second member will be None
Args:
package_or_versionstr (str): package version string
Returns:
tuple: (Version,int) : soft version on 4 members / packaging as an int
"""
if isinstance(package_or_versionstr,PackageEntry):
package_or_versionstr = package_or_versionstr.version
if isinstance(package_or_versionstr,Version):
return (Version(package_or_versionstr,4),None)
version_build = package_or_versionstr.split('-',1)
if len(version_build)>1:
return (Version(version_build[0],4),int(version_build[1]))
else:
return (Version(version_build[0],4),None)
class PackageRequest(BaseObjectClass):
"""Package and version request / condition
The request is the basic packagename(=version) request
Additional filters can be sepcified as arguments
The list filters are ordered from most preferred to least preferred options
Args:
request (str): packagename(<=>version)
architectures (list) : list of x64, x86
locales (list) : list of 2 letters lki
"""
_attributes = ['package','version','architectures','locales','maturities','min_os_version','max_os_version']
def __init__(self,request=None,copy_from=None,**kwargs):
self.package = None
self.version = None
self.architectures = None
self.locales = None
self.maturities = None
# boundaries are included
self.min_os_version = None
self.max_os_version = None
self._request = None
self._package = None
self._version_operator = None
self._version = None
self._architectures = None
self._locales = None
self._maturities = None
self._min_os_version = None
self._max_os_version = None
if copy_from is not None:
for k in self._attributes:
setattr(self,k,getattr(copy_from,k))
self.request = request
for (k,v) in kwargs.iteritems():
if hasattr(self,k):
setattr(self,k,v)
else:
raise Exception('PackageRequest has no attribute %s' % k)
@property
def request(self):
return self._request
@request.setter
def request(self,value):
self._request = value
if value:
package_version = REGEX_PACKAGE_CONDITION.match(value).groupdict()
self._package=package_version['package']
if package_version['operator'] is not None:
self._version_operator = package_version['operator']
else:
self._version_operator = '='
if package_version['version'] is not None:
self._version = PackageVersion(package_version['version'])
else:
self._version = None
else:
self._package = None
self._version = None
self._version_operator = None
@property
def version(self):
return self._version
@version.setter
def version(self,value):
if value is None:
self._version_operator = None
self._version = None
else:
package_version = REGEX_VERSION_CONDITION.match(value).groupdict()
if package_version['operator'] is not None:
self._version_operator = package_version['operator']
else:
self._version_operator = '='
if package_version['version'] is not None:
self._version = PackageVersion(package_version['version'])
else:
self._version = None
@property
def min_os_version(self):
return self._min_os_version
@min_os_version.setter
def min_os_version(self,value):
if value is not None and value != '':
self._min_os_version = Version(value)
else:
self._min_os_version = None
@property
def max_os_version(self):
return self._max_os_version
@max_os_version.setter
def max_os_version(self,value):
if value is not None and value != '':
self._max_os_version = Version(value)
else:
self._max_os_version = None
def _is_matched_version(self,version):
"""Return True if this request is verified by the provided version
Args:
version (str or Version): version to check against this request
Returns:
bool : True if version is verified by this request
"""
if self._version is None:
return True
else:
possibilities_dict = {
'>': (1,),
'<': (-1,),
'=': (0,),
'==': (0,),
'>=': (0, 1),
'<=': (-1, 0)
}
possibilities = possibilities_dict[self._version_operator]
if not isinstance(version,tuple):
version = PackageVersion(version)
if self._version[1] is None:
# omit packaging in comparison
cmp_res = cmp(version[0],self._version[0])
else:
cmp_res = cmp(version,self._version)
return cmp_res in possibilities
@property
def package(self):
return self._package or None
@package.setter
def package(self,value):
if value:
self._package = value
else:
self._package = None
@property
def architectures(self):
"""List of accepted architecturs"""
return self._architectures
@architectures.setter
def architectures(self,value):
if value in ('all','',None):
self._architectures = None
else:
self._architectures = ensure_list(value)
@property
def maturities(self):
"""List of accepted maturities"""
return self._maturities
@maturities.setter
def maturities(self,value):
"""List of accepted maturities"""
if value in ('all','',None):
self._maturities = None
else:
self._maturities = ensure_list(value,allow_none=True)
@property
def locales(self):
return self._locales
@locales.setter
def locales(self,value):
if value in ('all','',None):
self._locales = None
else:
self._locales = ensure_list(value)
def is_matched_by(self,package_entry):
"""Check if package_entry is matching this request"""
return (
(self.package is None or package_entry.package == self.package) and
self._is_matched_version(package_entry.version) and
(self.min_os_version is None or not package_entry.max_os_version or Version(package_entry.max_os_version)>=self.min_os_version) and
(self.max_os_version is None or not package_entry.min_os_version or Version(package_entry.min_os_version)<=self.max_os_version) and
(self.architectures is None or package_entry.architecture in ('','all') or package_entry.architecture in self.architectures) and
(self.locales is None or package_entry.locale in ('','all') or len(list_intersection(ensure_list(package_entry.locale),self.locales))>0) and
(self.maturities is None or (package_entry.maturity == '' and (self.maturities is None or 'PROD' in self.maturities)) or package_entry.maturity in self.maturities))
def __cmp__(self,other):
if isinstance(other,str) or isinstance(other,unicode):
other = PackageRequest(request=other)
if isinstance(other,PackageRequest):
return cmp((self.package,self.version,self.architectures,self.locales,self.maturities),(other.package,other.version,other.architectures,other.locales,other.maturities))
elif isinstance(other,PackageEntry):
if self.is_matched_by(other):
return 0
else:
return cmp((self.package,self.version,self.architectures,self.locales,self.maturities),(other.package,other.version,other.architecture,other.locale,other.maturity))
else:
raise Exception('Unsupported comparison between PackageRequest and %s' % other)
def __repr__(self):
def or_list(v):
if isinstance(v,list) or isinstance(v,tuple):
return u'|'.join(ensure_list(v))
else:
return v
attribs=[]
attribs.extend(["%s=%s" % (a,repr(getattr(self,a))) for a in self._attributes if getattr(self,a) is not None and getattr(self,a) != '' and getattr(self,a) != 'all'])
attribs = ','.join(attribs)
return "PackageRequest(%s)" % attribs
def __unicode__(self):
def or_list(v):
if isinstance(v,list) or isinstance(v,tuple):
return u','.join(ensure_list(v))
else:
return v
attribs=[]
attribs.extend([u"%s" % (ensure_unicode(or_list(getattr(self,a)))) for a in ['architectures','locales','maturities']
if getattr(self,a) is not None and getattr(self,a) != '' and getattr(self,a) != 'all'])
if attribs:
attribs = u' [%s]' % u'_'.join(attribs)
else:
attribs = ''
return "%s%s" % (self.request,attribs)
def compare_packages(self,pe1,pe2):
"""Compare packages taken in account the preferences from filter
"""
def _safe_rev_index(alist,avalue):
if avalue in ('','all'):
return -1000
elif alist and avalue in alist:
return -alist.index(avalue)
elif alist is None:
return avalue
else:
return -10000
t1 = (
pe1.package,
(self.version is None and '') or PackageVersion(pe1.version),
_safe_rev_index(self.architectures,pe1.architecture),
_safe_rev_index(self.locales,pe1.locale),
_safe_rev_index(self.maturities,pe1.maturity),
)
t2 = (
pe2.package,
(self.version is None and '') or PackageVersion(pe2.version),
_safe_rev_index(self.architectures,pe2.architecture),
_safe_rev_index(self.locales,pe2.locale),
_safe_rev_index(self.maturities,pe2.maturity),
)
return cmp(t1,t2)
def __iter__(self):
for key in self._attributes:
yield (key, getattr(self,key))
def control_to_dict(control,int_params=('size','installed_size')):
"""Convert a control file like object
key1: value1
key2: value2
...
list of lines into a dict
Multilines strings begins with a space
Breaks when an empty line is reached (limit between 2 package in Packages indexes)
Args:
control (file,str or list): file like object to read control from (until an empty line is reached)
int_params (list): attributes which must be converted to int
Returns:
dict
"""
result = {}
(key,value) = ('','')
linenr = 0
if isinstance(control,(unicode,str)):
control = control.splitlines()
while 1:
if isinstance(control,list):
if linenr>=len(control):
line = None
else:
line = control[linenr]
if not line or not line.strip():
break
else:
line = control.readline()
if not line or not line.strip():
break
if line.startswith(' '):
# additional lines begin with a space!
value = result[key]
value += '\n'
value += line.strip()
result[key] = value
else:
sc = line.find(':')
if sc<0:
raise EWaptBadControl(u'Invalid line (no ":" found) : %s' % line)
(key,value) = (line[:sc].strip(),line[sc+1:].strip())
key = key.lower()
if key in int_params:
try:
value = long(value)
except:
pass
result[key] = value
linenr += 1
return result
class PackageEntry(BaseObjectClass):
"""Manage package attributes coming from either control files in WAPT package, local DB, or developement dir.
Methods to build, unzip, sign or check a package.
Methods to sign the control attributes and check them.
>>> pe = PackageEntry('testgroup','0')
>>> pe.depends = 'tis-7zip'
>>> pe.section = 'group'
>>> pe.description = 'A test package'
>>> print(pe.ascontrol())
package : testgroup
version : 0
architecture : all
section : group
priority : optional
maintainer :
description : A test package
depends : tis-7zip
conflicts :
maturity :
locale :
min_os_version :
max_os_version :
min_wapt_version :
sources :
installed_size :
signer :
signer_fingerprint:
signature_date :
signed_attributes :
>>>
"""
# minim attributes for a valid control file
required_attributes = ['package','version','architecture','section','priority']
optional_attributes = ['maintainer','description','depends','conflicts','maturity',
'locale','target_os','min_os_version','max_os_version','min_wapt_version',
'sources','installed_size','impacted_process','description_fr','description_pl','description_de','description_es','audit_schedule',
'editor','keywords','licence','homepage','package_uuid']
# attributes which are added by _sign_control
signature_attributes = ['signer','signer_fingerprint','signature','signature_date','signed_attributes']
# these attrbutes are not written to Package control file, but only in Packages repository index
non_control_attributes = ['localpath','sourcespath','filename','size','repo_url','md5sum','repo']
# these attributes are not kept when duplicating / editing a package
not_duplicated_attributes = signature_attributes
# there files are not included in manifest file
manifest_filename_excludes = ['WAPT/signature','WAPT/signature.sha256','WAPT/manifest.sha256','WAPT/manifest.sha1']
_calculated_attributes = []
@property
def all_attributes(self):
return self.required_attributes + self.optional_attributes + self.signature_attributes + self.non_control_attributes + self._calculated_attributes
def get_default_signed_attributes(self):
all = self.required_attributes+self.optional_attributes+self.signature_attributes
all.remove('signature')
return all
def __init__(self,package='',version='0',repo='',waptfile=None, section = 'base',_default_md = 'sha256',**kwargs):
"""Initialize a Package entry with either attributes or an existing package file or directory.
Args:
waptfile (str): path to wapt zipped file or wapt development directory.
package (str) : package name
version (str) : package version
section (str): Type of package
base : any standard software install or configuration package with setup.py python code
restricted : same as base but is hidden by default in self service
group : group of packages, without setup.py. Only WAPT/control file.
host : host package without setup.py. Only WAPT/control file.
unit : AD Organizational unit package. Only WAPT/control file
profile : AD Group package. Only WAPT/control file
wsus : WAPT WUA Windows updates rules package with WAPT/control and WAPT/waptwua_rules.json file.
_default_md (str) : sh256 or sha1. hash function for signatures
any control attribute (str): initialize matching attribute
Returns:
None
"""
# temporary attributes added by join queries from local Wapt database
self._calculated_attributes=[]
self._package_content = None
self._control_updated = None
# init package attributes
for key in self.required_attributes:
setattr(self,key,'')
for key in self.optional_attributes:
setattr(self,key,'')
self.package=package
self.version=version
self.architecture='all'
self.section=section
self.priority='optional'
self.maintainer=''
self.description=''
self.depends=''
self.conflicts=''
self.sources=''
self.filename=''
self.size=None
self.maturity=''
self.signer=None
self.signer_fingerprint=None
self.signature=None
self.signature_date=None
self.signed_attributes=None
self.locale=''
self.target_os=''
self.min_os_version=''
self.max_os_version=''
self.min_wapt_version=''
self.installed_size=''
self.audit_schedule=''
self.impacted_process=''
self.keywords=''
self.editor=''
self.licence=''
self.homepage = ''
self.package_uuid = ''
self.md5sum=''
self.repo_url=''
self.repo=repo
# directory if unzipped package files
self.sourcespath=None
# full filename of package if built
self.localpath=None
self._control_updated = False
if waptfile:
if os.path.isfile(waptfile):
self.load_control_from_wapt(waptfile)
elif os.path.isdir(waptfile):
self.load_control_from_wapt(waptfile)
else:
raise EWaptBadControl(u'Package filename or directory %s does not exist' % waptfile)
self._default_md = _default_md
self._md = None
if kwargs:
for key,value in kwargs.iteritems():
if key in self.required_attributes + self.optional_attributes + self.non_control_attributes:
setattr(self,key,value)
def as_key(self):
return PackageKey(
package=self.package,
version=self.version,
architecture=self.architecture,
locale=self.locale if (self.locale is not None and self.locale != '' and self.locale != 'all') else '',
maturity=self.maturity if (self.maturity is not None and self.maturity != '' and self.maturity != 'all') else '',
)
def make_fallback_uuid(self):
return 'fb-%s' % (hashlib.sha256('-'.join([(self.package or '').encode('utf8'),str(self.architecture or ''),str(self.locale or ''),str(self.maturity or '')])).hexdigest(),)
def make_uuid(self):
self.package_uuid = str(uuid.uuid4())
return self.package_uuid
def as_package_request(self):
return PackageRequest(
package = self.package,
version=self.version,
architectures=[self.architecture],
locales=[self.locale],
maturities=[self.maturity],
)
def parse_version(self):
"""Parse version to major, minor, patch, pre-release, build parts.
"""
return parse_major_minor_patch_build(self.version)
def __getitem__(self,name):
if name is str or name is unicode:
name = name.lower()
if hasattr(self,name):
return getattr(self,name)
else:
raise Exception(u'No such attribute : %s' % name)
def __iter__(self):
for key in self.all_attributes:
if not key.startswith('_') or key == '_localized_description':
yield (key, getattr(self,key))
def as_dict(self):
return dict(self)
"""
def __unicode__(self):
return self.ascontrol(with_non_control_attributes=True)
def __str__(self):
return self.__unicode__()
"""
def __repr__(self):
return "PackageEntry(%s,%s %s)" % (repr(self.package),repr(self.version),
','.join(["%s=%s"%(key,repr(getattr(self,key))) for key in ('architecture','maturity','locale') if (getattr(self,key) is not None and getattr(self,key) != '' and getattr(self,key) != 'all')]))
def get(self,name,default=None):
"""Get PackageEntry property.
Args:
name (str): property to get. name is forced to lowercase.
default (any) : value to return in case the property doesn't not exist.
Returns:
any : property value
"""
if name is str or name is unicode:
name = name.lower()
if hasattr(self,name):
return getattr(self,name)
else:
return default
def get_localized_description(self,locale_code=None):
"""locale_code is a 2 chars code like fr or en or de"""
if locale_code is None:
return self.description
else:
if hasattr(self,'description_%s'%locale_code):
desc = getattr(self,'description_%s' % locale_code)
if desc is not None and desc != '':
return desc