-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathAptOfflineCoreLib.py
2506 lines (2130 loc) · 123 KB
/
AptOfflineCoreLib.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
############################################################################
# Copyright (C) 2005, 2020 Ritesh Raj Sarraf #
# rrs@researchut.com #
# #
# This program 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. #
# #
# This program 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 this program; if not, write to the #
# Free Software Foundation, Inc., #
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #
############################################################################
import os
import sys
import shutil
import platform
import string
import ssl
import urllib.request, urllib.error, urllib.parse
import http.client
import queue
import threading
import subprocess
import socket
import tempfile
import random # to generate random directory names for installing multiple bundles in on go
import zipfile
import pydoc
import traceback
import argparse
from ssl import SSLError, SSLEOFError
import zlib
from apt_offline_core.AptOfflineLib import AptOfflineErrors, AptOfflineLibShutilError
FCNTL_LOCK = True
try:
import fcntl
except ImportError:
# Only available on platform Unix
FCNTL_LOCK = False
# On Debian, python-debianbts package provides this library
DebianBTS = True
try:
import debianbts
except ImportError:
try:
from apt_offline_core import AptOfflineDebianBtsLib as debianbts
except ImportError:
DebianBTS = False
try:
MagicLib = True
from apt_offline_core import AptOfflineMagicLib
except TypeError:
''' On Windows, the file magic library does not work '''
MagicLib = False
except AttributeError:
# On Linux, make sure libmagic is installed
MagicLib = False
#INFO: added to handle GUI interaction
guiBool = False
guiTerminateSignal = False # cancelling a download
guiMetaCompleted = False
totalSize = [0,0] # total_size, current_total
#INFO: Check if python-apt is installed
PythonApt = False
try:
import apt
import apt_pkg
from apt.debfile import DebPackage
PythonApt = True
except ImportError:
PythonApt = False
from apt_offline_core import AptOfflineLib
#INFO: Set the default timeout to 30 seconds for the packages that are being downloaded.
socket.setdefaulttimeout(30)
# How many times should we retry on socket timeouts
SOCKET_TIMEOUT_RETRY = 5
'''This is the core module. It does the main job of downloading packages/update packages,\n
figuring out if the packages are in the local cache, handling exceptions and many more stuff'''
app_name = "apt-offline"
version = "1.8.5"
myCopyright = "(C) 2005 - 2022 Ritesh Raj Sarraf"
terminal_license = "This program comes with ABSOLUTELY NO WARRANTY.\n\
This is free software, and you are welcome to redistribute it under\n\
the GNU GPL Version 3 (or later) License\n"
errlist = []
supported_platforms = ["Linux", "GNU/kFreeBSD", "GNU"]
apt_update_target_path = '/var/lib/apt/lists/partial'
apt_update_final_path = '/var/lib/apt/lists/'
apt_package_target_path = '/var/cache/apt/archives/partial/'
apt_package_final_path = '/var/cache/apt/archives/'
# Locks
apt_lists_lock = '/var/lib/apt/lists/lock'
apt_packages_lock = '/var/cache/apt/archives/lock'
apt_bug_file_format = "__apt__bug__report"
#These are spaces which will overwrite the progressbar left mess
LINE_OVERWRITE_SMALL = " " * 10
LINE_OVERWRITE_MID = " " * 30
LINE_OVERWRITE_FULL = " " * 60
Bool_Verbose = False
#Bool_TestWindows = True
log = AptOfflineLib.Log( Bool_Verbose, lock=True )
class FetchBugReports:
def __init__( self, apt_bug_file_format, ArchiveFile=None, lock=False, DownloadDir=None ):
self.bugsList = []
self.lock = lock
self.apt_bug = apt_bug_file_format
self.DownloadDir = DownloadDir
self.ArchiveFile = ArchiveFile
self.fileMgmt = AptOfflineLib.FileMgmt()
def FetchBugsDebian( self, PackageName):
'''0 => False
1 => No Bug Reports
2 => True'''
try:
self.bugs_list = debianbts.get_bugs(package=PackageName)
num_of_bugs = len(self.bugs_list)
except Exception:
log.err(traceback.format_exc())
log.err("Foreign exception raised in module debianbts\n")
log.err("Failed to download bug report for package %s\n" % (PackageName))
return 0
if num_of_bugs:
atleast_one_bug_report_downloaded = False
for eachBug in self.bugs_list:
# Fetch bug report..
# TODO: Handle exceptions later
try:
bugReport = debianbts.get_bug_log(eachBug)
except Exception:
#INFO: Some of these exceptions are sporadic. For example, this one was hit because of network timeout
# And we don't want the entire operation to fail because of this
log.warn("Foreign exception raised in module debianbts\n")
log.warn("Failed to download bug report for %s\nWill continue to download others\n" % (eachBug))
log.err(traceback.format_exc())
continue
# This tells us how many follow-ups for the bug report are present.
bugReportLength = bugReport.__len__()
writeBugReport = 0
self.fileName = os.path.join(tempfile.gettempdir(), PackageName + "{}" + str(eachBug) + "{}" + self.apt_bug)
file_handle = open( self.fileName, 'w', encoding='utf-8')
#TODO: Can we manipulate these headers in a more efficient way???
for line in bugReport[writeBugReport]['header'].split("\n"):
if line.startswith("Subject:"):
file_handle.write(line)
file_handle.write("\n")
break
while writeBugReport < bugReportLength:
file_handle.write(bugReport[writeBugReport]['body'])
file_handle.write("\n\n")
writeBugReport += 1
if writeBugReport < bugReportLength:
file_handle.write("Follow-Up #%d\n\n" % writeBugReport)
file_handle.flush()
file_handle.close()
#We're adding to an archive file here.
if self.ArchiveFile:
if self.AddToArchive( self.ArchiveFile, self.fileName ):
log.verbose("%s added to file %s\n" % (self.fileName, self.ArchiveFile))
else:
log.warn("%s failed to be added to file %s\n" % (self.fileName, self.ArchiveFile))
elif self.DownloadDir:
try:
if self.fileMgmt.move_file(self.fileName, self.DownloadDir):
log.verbose("%s added to download dir %s\n" % (self.fileName, self.DownloadDir))
except AptOfflineLibShutilError as msg:
log.warn("%s\n" % (msg))
atleast_one_bug_report_downloaded = True
if atleast_one_bug_report_downloaded:
return 2
else:
return 1
else:
#FIXME: When no bug reports are there, i.e. bug count is 0, we hit here
# We shouldn't be returning False
return 1
def AddToArchive(self, ArchiveFile, fileName):
try:
if self.compress_the_file(ArchiveFile, fileName):
if self.file_possibly_deleted is not True:
os.unlink(fileName)
except AptOfflineErrors as message:
log.warn("%s\n" % (message))
return True
class ExecCmd:
def __init__(self, Simulate=False):
self.Simulate = Simulate
def Simulate(self):
if self.Simulate is True:
pass
def ExecSystemCmd(self, cmd, sigFile=None):
'''
Execute command 'cmd' with subprocess module
Write stdout to sigFile, if provided
'''
if self.Simulate:
return True
if sigFile is None: #subprocess.call does take None as an arg
fh = None
else:
try:
fh = open(sigFile, 'a')
except Exception:
log.verbose(traceback.format_exc())
return False
if fh is not None:
preState = fh.tell()
log.verbose("Command is: %s\n" % (cmd))
p = subprocess.call(cmd, universal_newlines=True, stdout=fh)
if fh is not None:
fh.flush()
if p != 0:
#INFO: stderr will give us junk which our stripper() will not understand
# So, under that condition, truncate the data so that at least, our
# sig file is still usable
if fh is not None:
fh.truncate(preState)
fh.flush()
return False
return True
class AptManip(ExecCmd):
def __init__(self, OutputFile, Simulate=False, AptType="apt-get", AptReinstall=False):
ExecCmd.__init__(self, Simulate)
self.WriteTo = OutputFile
self.AptReinstall = AptReinstall
self.ShouldSimulate = Simulate
if AptType == "apt":
self.apt = "apt"
elif AptType == "apt-get":
self.apt = "apt-get"
elif AptType == "aptitude":
self.apt = "aptitude"
elif AptType == "python-apt":
self.apt = "python-apt"
else:
self.apt = "apt-get"
def Update(self):
log.verbose("APT Update Method is of type: %s\n" % self.apt)
if self.apt == "apt-get":
self.__AptGetUpdate()
elif self.apt == "apt":
self.__AptUpdate()
elif self.apt == "aptitude":
pass
elif self.apt == "python-apt":
self.__PythonAptUpdate()
else:
log.err("Method not supported")
sys.exit(1)
def Upgrade(self, UpgradeType="upgrade", ReleaseType=None):
log.verbose("APT Upgrade Method is of type: %s\n" % self.apt)
if self.apt == "apt-get":
return self.__AptGetUpgrade(UpgradeType, ReleaseType)
elif self.apt == "apt":
return self.__AptUpgrade(UpgradeType, ReleaseType)
elif self.apt == "aptitude":
pass
elif self.apt == "python-apt":
# Upgrade is broken in python-apt
# Hence for now, redirect to apt-get
return self.__PythonAptUpgrade(UpgradeType, ReleaseType)
else:
log.err("Method not supported")
sys.exit(1)
def InstallPackages(self, PackageList, ReleaseType):
log.verbose("APT Install Method is of type: %s\n" % self.apt)
if self.apt == "apt-get":
return self.__AptGetInstallPackage(PackageList, ReleaseType)
elif self.apt == "apt":
return self.__AptInstallPackage(PackageList, ReleaseType)
elif self.apt == "python-apt":
return self.__AptInstallPackage(PackageList, ReleaseType)
else:
log.err("Method not supported")
sys.exit(1)
def InstallSrcPackages(self, SrcPackageList, ReleaseType, BuildDependency):
log.verbose("APT Install Source Method is of type: %s\n" % self.apt)
if self.apt == "apt-get":
return self.__AptGetInstallSrcPackages(SrcPackageList, ReleaseType, BuildDependency)
elif self.apt == "apt":
return self.__AptInstallSrcPackages(SrcPackageList, ReleaseType, BuildDependency)
elif self.apt == "python-apt":
return self.__AptInstallSrcPackages(SrcPackageList, ReleaseType, BuildDependency)
else:
log.err("Method not supported")
sys.exit(1)
def __FixAptSigs(self):
if self.ShouldSimulate is True:
log.msg("In simulation mode, no changes applied\n")
else:
for localFile in os.listdir(apt_update_target_path):
if localFile.endswith(".gpg.reverify"):
sig_file = localFile.rstrip(".reverify")
log.verbose("Recovering gpg signature %s.\n" % (localFile) )
localFile = os.path.join(apt_update_target_path, localFile)
os.rename(localFile, os.path.join(apt_update_final_path + sig_file) )
def __AptUpdate(self):
log.msg("Gathering details needed for 'update' operation\n")
if self.ExecSystemCmd(["/usr/bin/apt", "-qq", "--print-uris", "update"], self.WriteTo) is False:
log.verbose( "FATAL: Something is wrong with the apt system.\n" )
return False
log.verbose("Calling __FixAptSigs to fix the apt sig problem")
self.__FixAptSigs()
def __AptGetUpdate(self):
log.msg("Gathering details needed for 'update' operation\n")
if self.ExecSystemCmd(["/usr/bin/apt-get", "-q", "--print-uris", "update"], self.WriteTo) is False:
log.verbose( "FATAL: Something is wrong with the apt system.\n" )
return False
log.verbose("Calling __FixAptSigs to fix the apt sig problem")
self.__FixAptSigs()
def __AptitudeUpdate(self):
pass
def __PythonAptUpdate(self):
log.verbose("Open file %s for write" % self.WriteTo)
try:
self.writeFH = open(self.WriteTo, 'a')
except Exception:
log.verbose(traceback.format_exc())
log.err("Failed to open file %s for write. Exiting\n" % (self.WriteTo))
sys.exit(1)
log.msg("Gathering details needed for 'update' operation\n")
log.verbose("\nUsing Python apt interface\n")
apt_pkg.init_config()
apt_pkg.init_system()
acquire = apt_pkg.Acquire()
slist = apt_pkg.SourceList()
# Read the main list
slist.read_main_list()
# Add all indexes to the fetcher
slist.get_indexes(acquire, True)
# Now write the URI of every item
for item in acquire.items:
#INFO: For update files, there's no checksum present.
# Also, their size is not determined.
# Hence filesize is always returned '0'
# And checksum is something I'm writing as ':'
# We strip item.destfile because that's how apt-get had historically presented it to us
destFile = item.destfile.split("/")[-1]
self.writeFH.write("'" + item.desc_uri + "'" + " " + destFile + " " + str(item.filesize) + " " + ":" + "\n")
log.verbose("Writing string %s %s %d %s to file %s\n" % (item.desc_uri, destFile, item.filesize, ":", self.WriteTo) )
self.writeFH.flush()
self.writeFH.close()
def __PythonAptUpgrade(self, UpgradeType="upgrade", ReleaseType=None):
log.verbose("Open file %s for write\n" % self.WriteTo)
try:
self.writeFH = open(self.WriteTo, 'a')
except Exception:
log.verbose(traceback.format_exc())
log.err("Failed to open file %s for write. Exiting\n")
sys.exit(1)
log.msg("Gathering details needed for 'upgrade' operation\n")
log.warn("Option --upgrade-type not supported with this backend\n")
log.verbose("\nUsing Python apt interface\n")
cache = apt.Cache()
cache.open(None)
if UpgradeType == "dist-upgrade":
cache.upgrade(dist_upgrade=True)
elif UpgradeType == "upgrade":
cache.upgrade(dist_upgrade=False)
else:
cache.upgrade()
for pkg in cache.get_changes():
log.verbose("Generable data is: %s %s %d %s\n" % (pkg.candidate.uri, pkg.candidate.filename.split('/')[-1], pkg.candidate.size, pkg.candidate.md5))
self.writeFH.write("%s %s %d %s\n" % (pkg.candidate.uri, pkg.candidate.filename.split('/')[-1], pkg.candidate.size, pkg.candidate.md5))
self.writeFH.flush()
self.writeFH.close()
def __AptUpgrade(self, UpgradeType="upgrade", ReleaseType=None):
self.ReleaseType = ReleaseType
if ReleaseType is not None:
cmd = ["/usr/bin/apt", "-qqq", "--print-uris", "-t"]
cmd.append(self.ReleaseType)
cmd.append(UpgradeType)
else:
cmd = ["/usr/bin/apt", "-qqq", "--print-uris"]
cmd.append(UpgradeType)
log.msg("Gathering details needed for '%s' operation\n" % (UpgradeType) )
if self.ExecSystemCmd(cmd, self.WriteTo) is False:
log.verbose("FATAL: Something is wrong with the APT system\n")
return False
def __AptGetUpgrade(self, UpgradeType="upgrade", ReleaseType=None):
self.ReleaseType = ReleaseType
if ReleaseType is not None:
cmd = ["/usr/bin/apt-get", "-qq", "--print-uris", "-t"]
cmd.append(self.ReleaseType)
cmd.append(UpgradeType)
else:
cmd = ["/usr/bin/apt-get", "-qq", "--print-uris"]
cmd.append(UpgradeType)
log.msg("Gathering details needed for '%s' operation\n" % (UpgradeType) )
if self.ExecSystemCmd(cmd, self.WriteTo) is False:
log.verbose("FATAL: Something is wrong with the APT system\n")
return False
def __AptInstallPackage(self, PackageList=None, ReleaseType=None):
self.ReleaseType = ReleaseType
log.msg("Gathering installation details for package %s\n" % (PackageList) )
if self.ReleaseType is not None:
cmd = ["/usr/bin/apt", "-qqq", "--print-uris", "install", "-t"]
cmd.append(self.ReleaseType)
else:
cmd = ["/usr/bin/apt", "-qqq", "--print-uris", "install"]
for pkg in PackageList:
cmd.append(pkg)
if self.ExecSystemCmd(cmd, self.WriteTo) is False:
log.verbose( "FATAL: Something is wrong with the apt system.\n" )
return False
def __AptInstallSrcPackages(self, SrcPackageList=None, ReleaseType=None, BuildDependency=False):
self.ReleaseType = ReleaseType
log.msg("Gathering installation details for source package %s\n" % (SrcPackageList) )
if self.ReleaseType is not None:
cmd = ["/usr/bin/apt", "-qqq", "--print-uris", "source", "-t"]
cmd.append(self.ReleaseType)
cmdBuildDep = ["/usr/bin/apt", "-qqq", "--print-uris", "build-dep", "-t"]
cmdBuildDep.append(self.ReleaseType)
else:
cmd = ["/usr/bin/apt", "-qqq", "--print-uris", "source"]
cmdBuildDep = ["/usr/bin/apt", "-qqq", "--print-uris", "build-dep"]
for pkg in SrcPackageList:
cmd.append(pkg)
cmdBuildDep.append(pkg)
if self.ExecSystemCmd(cmd, self.WriteTo) is False:
log.verbose( "FATAL: Something is wrong with the apt system.\n" )
return False
if BuildDependency:
log.msg("Generating Build-Dependency for source packages %s.\n" % (SrcPackageList) )
if self.ExecSystemCmd(cmdBuildDep, self.WriteTo) is False:
log.verbose( "FATAL: Something is wrong with the apt system.\n" )
return False
def __AptGetInstallPackage(self, PackageList=None, ReleaseType=None):
self.ReleaseType = ReleaseType
log.msg("Gathering installation details for package %s\n" % (PackageList) )
if self.ReleaseType is not None:
cmd = ["/usr/bin/apt-get", "-qq", "--print-uris", "install", "-t"]
cmd.append(self.ReleaseType)
else:
cmd = ["/usr/bin/apt-get", "-qq", "--print-uris", "install"]
for pkg in PackageList:
cmd.append(pkg)
if self.ExecSystemCmd(cmd, self.WriteTo) is False:
log.verbose( "FATAL: Something is wrong with the apt system.\n" )
return False
def __AptGetInstallSrcPackages(self, SrcPackageList=None, ReleaseType=None, BuildDependency=False):
self.ReleaseType = ReleaseType
log.msg("Gathering installation details for source package %s\n" % (SrcPackageList) )
if self.ReleaseType is not None:
cmd = ["/usr/bin/apt-get", "-qq", "--print-uris", "source", "-t"]
cmd.append(self.ReleaseType)
cmdBuildDep = ["/usr/bin/apt-get", "-qq", "--print-uris", "build-dep", "-t"]
cmdBuildDep.append(self.ReleaseType)
else:
cmd = ["/usr/bin/apt-get", "-qq", "--print-uris", "source"]
cmdBuildDep = ["/usr/bin/apt-get", "-qq", "--print-uris", "build-dep"]
for pkg in SrcPackageList:
cmd.append(pkg)
cmdBuildDep.append(pkg)
if self.ExecSystemCmd(cmd, self.WriteTo) is False:
log.verbose( "FATAL: Something is wrong with the apt system.\n" )
return False
if BuildDependency:
log.msg("Generating Build-Dependency for source packages %s.\n" % (SrcPackageList) )
if self.ExecSystemCmd(cmdBuildDep, self.WriteTo) is False:
log.verbose( "FATAL: Something is wrong with the apt system.\n" )
return False
class APTVerifySigs(ExecCmd):
def __init__(self, gpgv=None, keyring=None, Simulate=False):
'''
Initialize keyring based on environment
Uses python-apt or apt-config
'''
ExecCmd.__init__(self, Simulate)
self.defaultPaths = []
if PythonApt is True:
apt_pkg.init()
self.defaultPaths.append(apt_pkg.config.find_dir('Dir::Etc::trustedparts'))
self.defaultPaths.append(apt_pkg.config.find_file('Dir::Etc::trusted'))
else:
command = b"""
# Unset variables in case they are set already
unset trusted
unset trustedparts
# Get the variables from apt
eval $(apt-config shell trusted Dir::Etc::trusted/f)
eval $(apt-config shell trustedparts Dir::Etc::trustedparts/d)
# Securely pass the variables back to python-apt
printf "%s\\0%s" "$trusted" "$trustedparts"
"""
process = subprocess.Popen(['sh'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
output = process.communicate(input=command)[0]
trusted, trustedparts = output.decode('utf-8').split('\x00')
log.verbose("trusted is %s and trustedparts is %s\n" % (trusted, trustedparts))
self.defaultPaths.append(trusted)
self.defaultPaths.append(trustedparts)
log.verbose("APT Signature verification path is: %s\n" % self.defaultPaths)
if gpgv is None:
self.gpgv="/usr/bin/gpgv"
else:
self.gpgv=gpgv
self.opts = []
if keyring is None:
self.opts.append("--ignore-time-conflict")
for eachPath in self.defaultPaths:
if os.path.isfile(eachPath):
if eachPath.endswith(".asc"):
self.DearmorSig(eachPath)
elif eachPath.endswith(".gpg"):
self.opts.extend(["--keyring", eachPath])
elif os.path.isdir(eachPath):
for eachGPG in os.listdir(eachPath):
if eachGPG.endswith(".asc"):
eachGPG = os.path.join(eachPath, eachGPG)
self.DearmorSig(eachGPG)
elif eachGPG.endswith(".gpg"):
eachGPG = os.path.join(eachPath, eachGPG)
log.verbose("Adding %s to the apt-offline keyring\n" % (eachGPG) )
self.opts.extend(["--keyring", eachGPG])
if len(self.opts) == 1:
log.err("No valid keyring paths found in: %s\n" % (", ".join(self.defaultPaths)))
else:
self.opts.extend(["--keyring", keyring, "--ignore-time-conflict"])
def DearmorSig(self, asciiSig):
gpgCmd = []
gpgKeyringFile = tempfile.mktemp()
gpgCmd.append("/usr/bin/gpg")
gpgCmd.extend(["--output", gpgKeyringFile])
gpgCmd.extend(["--dearmor", asciiSig])
if self.ExecSystemCmd(gpgCmd, None):
self.opts.extend(["--keyring", gpgKeyringFile])
else:
log.error("Failed to dearmor gpg signature file %s\n", (asciiSig))
def VerifySig(self, signature_file, signed_file):
if not os.access(signature_file, os.F_OK):
log.err("%s is bad. Can't proceed.\n" % (signature_file) )
return False
if not os.access(signed_file, os.F_OK):
log.err("%s is bad. Can't proceed.\n" % (signed_file) )
return False
#INFO: Commands can escape and inject. So carefully craft the command
# Thanks: Bernd Dietzel
gpgvCmd = []
gpgvCmd.append(self.gpgv)
gpgvCmd.extend(self.opts)
gpgvCmd.append(signature_file)
gpgvCmd.append(signed_file)
return self.ExecSystemCmd(gpgvCmd, None)
def VerifyFile(self, signed_file):
# Verify a self signed file
if not os.access(signed_file, os.F_OK):
log.err("%s is bad. Can't proceed.\n" % (signed_file) )
return False
gpgvCmd = []
gpgvCmd.append(self.gpgv)
gpgvCmd.extend(self.opts)
gpgvCmd.append(signed_file)
return self.ExecSystemCmd(gpgvCmd, None)
class LockAPT:
'''Manipulate locks on the APT Database'''
def __init__(self, lists, packages):
try:
self.listLock = os.open(lists, os.O_RDWR | os.O_TRUNC | os.O_CREAT, 0o640)
self.pkgLock = os.open(packages, os.O_RDWR | os.O_TRUNC | os.O_CREAT, 0o640)
except Exception:
log.verbose(traceback.format_exc())
log.err("Couldn't open lockfile\n")
sys.exit(1)
def lockLists(self):
try:
fcntl.lockf(self.listLock, fcntl.LOCK_EX | fcntl.LOCK_NB)
return True
except Exception:
log.verbose(traceback.format_exc())
return False
def lockPackages(self):
try:
fcntl.lockf(self.pkgLock, fcntl.LOCK_EX | fcntl.LOCK_NB)
return True
except Exception:
log.verbose(traceback.format_exc())
return False
def unlockLists(self):
try:
fcntl.lockf(self.listLock, fcntl.LOCK_UN)
return True
except Exception:
log.verbose(traceback.format_exc())
return False
def unlockPackages(self):
try:
fcntl.lockf(self.pkgLock, fcntl.LOCK_UN)
return True
except Exception:
log.verbose(traceback.format_exc())
return False
class GenericDownloadFunction():
def download_from_web(self, url, localFile, download_dir):
'''url = url to fetch
localFile = file to save to
donwload_dir = download path'''
block_size = 4096
i = 0
counter = 0
os.chdir(download_dir)
try:
temp = urllib.request.urlopen(url)
headers = temp.info()
size = int(headers['Content-Length'])
#INFO: Add the download thread into the Global ProgressBar Thread
self.addItem(size)
except urllib.error.HTTPError as errstring:
errfunc(errstring.code, errstring.reason, url)
return False
except urllib.error.URLError as errstring:
#INFO: Weird. But in urllib2.URLError, I noticed that for
# error type "timeouts", no errno was defined.
# errstring.errno was listed as None
# In my tests, wget categorized this behavior as:
# 504: gateway timeout
# So I am doing the same here.
if errstring.errno is None:
errfunc(504, errstring.reason, url)
else:
errfunc(errstring.errno, errstring.reason, url)
return False
except http.client.HTTPException as e:
log.err("Type HTTPException occurred while processing url: %s\n" % (url))
log.err("Failed to download %s\n" % (localFile))
if type(e) is str:
log.err(e)
return False
except http.client.BadStatusLine as e:
#INFO: See Python Bug: https://bugs.python.org/issue8823
log.err("BadStatusLine exception: Python Bug 8823\n")
log.err("Type BadStatusLine occurred while processing url: %s\n" % (url))
log.err("Failed to download %s\n" % (localFile))
if type(e) is str:
log.err(e)
return False
except socket.timeout:
log.err("Socket timeout. Skipping URL: %s\n" % (url))
return False
data = open(localFile,'wb')
socket_counter = 0
while i < size:
socket_timeout = None
try:
data.write (temp.read(block_size))
except socket.timeout:
socket_timeout = True
socket_counter += 1
except socket.error:
socket_timeout = True
socket_counter += 1
if socket_counter == SOCKET_TIMEOUT_RETRY:
errfunc(101010, "Max timeout retry count reached. Discontinuing download.\n", url)
# Clean the half downloaded file.
data.close()
os.unlink(localFile)
return False
if socket_timeout is True:
errfunc(10054, "Socket Timeout. Retry - %d\n" % (socket_counter) , url)
continue
increment = min(block_size, size - i)
i += block_size
counter += 1
self.updateValue(increment)
#REAL_PROGRESS: update current total in totalSize
if guiBool and not guiTerminateSignal:
totalSize[1] += block_size
if guiTerminateSignal:
data.close()
temp.close()
return False
self.completed()
data.close()
temp.close()
return True
# #FIXME: Find out optimal fix for this exception handling
# except OSError as erret:
# (errno, strerror) = erret
# errfunc(errno, strerror, download_dir)
# except IOError as e:
# if hasattr(e, 'reason'):
# log.err("%s\n" % (e.reason))
# if hasattr(e, 'code') and hasattr(e, 'reason'):
# errfunc(e.code, e.reason, localFile)
# except socket.timeout:
# errfunc(10054, "Socket timeout.\n", url)
class DownloadFromWebDisplay(AptOfflineLib.ProgressBar, GenericDownloadFunction):
'''Class for DownloadFromWeb
This class also inherits progressbar functionalities from
parent class, ProgressBar'''
def __init__(self, width, total_items):
'''width = Progress Bar width'''
AptOfflineLib.ProgressBar.__init__(self, width=width, total_items=total_items)
class DownloadFromWebQuiet(AptOfflineLib.ProgressBar, GenericDownloadFunction):
'''Class for DownloadFromWeb
This class also inherits progressbar functionalities from
parent class, ProgressBar'''
def __init__(self, width, total_items):
'''width = Progress Bar width'''
AptOfflineLib.ProgressBar.__init__(self, width=width, total_items=total_items)
def display(self):
return
def stripper(item):
'''Strips extra characters from "item".
Breaks "item" into:
url - The URL
localFile - The actual package file
size - The file size
checksum - The checksum string
and returns them.'''
log.verbose("Item before split is: %s\n" % (item))
SplitItem = item.split(' ')
url = SplitItem[0].strip("'").strip()
localFile = SplitItem[1].strip("'").strip()
size = SplitItem[2].strip("'").strip()
try:
checksum = SplitItem[3].strip("'").strip()
except IndexError:
checksum = None
log.verbose("line %s is missing checksum entry" % (item))
log.verbose("Items after split is: %s\n" % (SplitItem))
# Convert size to integer
size = int(size) if size.isdecimal() else 0
log.verbose("size of size is: %s\n" % (size))
return (url, localFile, size, checksum)
def errfunc(errno, errormsg, filename):
'''We use errfunc to handler errors.
There are some error codes (-3 and 13 as of now)
which are temporary codes, they happen when there
is a temporary resolution failure, for example.
For such situations, we can't abort because the
uri file might have other hosts also, which might
be well accessible.
This function does the job of behaving accordingly
as per the error codes.'''
retriable_error_codes = [-3, 13, 404, 403, 401, 429, 10060, 104, 101010]
# 104, 'Connection reset by peer'
# 504 is for gateway timeout
# 429 Too Many Requests
# 404 is for URL error. Page not found.
# 401 is for Restricted pages
# 10060 is for Operation Time out. There can be multiple reasons for this timeout
# 101010 is for socket max retry count
# 10054 is for Socket Timeout. Socket Timeout are seen during network congestion
#TODO: Find out what these error codes are for
# and better document them the next time you find it out.
# 13 is for "Permission Denied" when you don't have privileges to access the destination
if errno in retriable_error_codes:
log.verbose("%s - %s - %s %s\n" % (filename, errno, errormsg, LINE_OVERWRITE_FULL))
log.verbose("Will still try with other package uris\n")
elif errno == 10054:
log.err("%s - %s - %s %s\n" % (filename, errno, errormsg, LINE_OVERWRITE_FULL) )
elif errno == 504:
log.err("%s failed with error %s:%s %s\n" % (filename, errno, errormsg, LINE_OVERWRITE_FULL))
errlist.append(filename)
elif errno == 407 or errno == 2:
# These, I believe are from OSError/IOError exception.
# I'll document it as soon as I confirm it.
log.err("%s\n" % (errormsg))
sys.exit(errno)
elif errno == 1:
log.err(errormsg)
log.err("Explicit program termination %s\n" % (errno))
sys.exit(errno)
else:
log.err("I don't understand this error code %s\nPlease file a bug report\n" % (errno))
def fetcher( args ):
# get opts
Str_GetArg = args.get
Int_SocketTimeout = args.socket_timeout
Str_DownloadDir = args.download_dir
Str_CacheDir = args.cache_dir
Bool_DisableMD5Check = args.disable_md5check
Int_NumOfThreads = args.num_of_threads
Str_BundleFile = args.bundle_file
Str_ProxyHost = args.proxy_host
Str_ProxyPort = args.proxy_port
Str_HttpsCertFile = args.https_cert_file
Str_HttpsKeyFile = args.https_key_file
Str_HttpBasicAuth = args.http_basicauth
Bool_DisableCertCheck = args.disable_cert_check
Bool_BugReports = args.deb_bugs
global guiTerminateSignal
if Int_SocketTimeout:
try:
Int_SocketTimeout.__int__()
socket.setdefaulttimeout( Int_SocketTimeout )
log.verbose( "Default timeout now is: %d.\n" % ( socket.getdefaulttimeout() ) )
except AttributeError:
log.err( "Incorrect value set for socket timeout.\n" )
sys.exit( 1 )
if Str_ProxyHost:
if Str_ProxyPort:
log.verbose(Str_ProxyHost + ":" + str(Str_ProxyPort))
proxy_support = urllib.request.ProxyHandler({'http': Str_ProxyHost + ":" + str(Str_ProxyPort), 'https': Str_ProxyHost + ":" + str(Str_ProxyPort)})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
log.verbose("Proxy successfully set up with Host %s and port %s\n" % (Str_ProxyHost, str(Str_ProxyPort)))
else:
proxy_support = urllib.request.ProxyHandler({'http': Str_ProxyHost, 'https': Str_ProxyHost})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
log.verbose("Proxy successfully set up with Host %s and default port\n" % (Str_ProxyHost) )
if (Str_HttpsCertFile and Str_HttpsKeyFile) or Bool_DisableCertCheck:
context = ssl.create_default_context()
if Bool_DisableCertCheck:
log.verbose("certificate checks for servers are ignored")
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
if Str_HttpsCertFile and Str_HttpsKeyFile:
log.verbose("cert-file:" + Str_HttpsCertFile + " key-file:" + Str_HttpsKeyFile)
context.load_cert_chain(Str_HttpsCertFile, Str_HttpsKeyFile)
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context))
urllib.request.install_opener(opener)
log.verbose("SSL Client Authentication successfully set up with certificate file %s and key file %s\n" % (Str_HttpsCertFile, Str_HttpsKeyFile))
if Str_HttpBasicAuth:
# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
try:
for authstr in Str_HttpBasicAuth:
# Add the username and password.
parsedUrl = urllib.parse.urlparse(authstr)
username = parsedUrl.username
password = urllib.parse.unquote(parsedUrl.password)
top_level_url = parsedUrl.hostname
password_mgr.add_password(None, top_level_url, username, password)
log.verbose("Added user %s with pass %s auth to domain %s\n" % (username, password, top_level_url))
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)