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
|
# Copyright 2009 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Infrastructure for handling custom uploads.
Custom uploads are uploaded to Soyuz as special tarballs that must be
extracted to a particular location in the archive. This module
contains code common to the different custom upload types.
Custom uploads include Debian installer packages, dist upgraders and
DDTP (Debian Description Translation Project) tarballs.
"""
__metaclass__ = type
__all__ = ['CustomUpload', 'CustomUploadError']
import os
import shutil
import tarfile
import tempfile
from lp.archivepublisher.debversion import (
Version as make_version,
VersionError,
)
class CustomUploadError(Exception):
"""Base class for all errors associated with publishing custom uploads."""
class CustomUploadTarballTarError(CustomUploadError):
"""The tarfile module raised an exception."""
def __init__(self, tarfile_path, tar_error):
message = 'Problem reading tarfile %s: %s' % (tarfile_path, tar_error)
CustomUploadError.__init__(self, message)
class CustomUploadTarballInvalidTarfile(CustomUploadError):
"""The supplied tarfile did not contain the expected elements."""
def __init__(self, tarfile_path, expected_dir):
message = ('Tarfile %s did not contain expected file %s' %
(tarfile_path, expected_dir))
CustomUploadError.__init__(self, message)
class CustomUploadBadUmask(CustomUploadError):
"""The environment's umask was incorrect."""
def __init__(self, expected_umask, got_umask):
message = 'Bad umask; expected %03o, got %03o' % (
expected_umask, got_umask)
CustomUploadError.__init__(self, message)
class CustomUploadTarballInvalidFileType(CustomUploadError):
"""A file of type other than regular or symlink was found."""
def __init__(self, tarfile_path, file_name):
message = ("Tarfile %s has file %s which is not a regular file, "
"directory or a symlink" % (tarfile_path, file_name))
CustomUploadError.__init__(self, message)
class CustomUploadTarballBadSymLink(CustomUploadError):
"""A symlink was found whose target points outside the immediate tree."""
def __init__(self, tarfile_path, symlink_name, target):
message = "Tarfile %s has a symlink %s whose target %s is illegal" % (
tarfile_path, symlink_name, target)
CustomUploadError.__init__(self, message)
class CustomUploadTarballBadFile(CustomUploadError):
"""A file was found which resolves outside the immediate tree.
This can happen if someone embeds ../file in the tar, for example.
"""
def __init__(self, tarfile_path, file_name):
message = "Tarfile %s has a file %s which is illegal" % (
tarfile_path, file_name)
CustomUploadError.__init__(self, message)
class CustomUpload:
"""Base class for custom upload handlers"""
# The following should be overriden by subclasses, probably in
# their __init__
targetdir = None
version = None
def __init__(self, archive_root, tarfile_path, distroseries):
self.archive_root = archive_root
self.tarfile_path = tarfile_path
self.distroseries = distroseries
self.tmpdir = None
def process(self):
"""Process the upload and install it into the archive."""
try:
self.extract()
self.installFiles()
self.fixCurrentSymlink()
finally:
self.cleanup()
def verifyBeforeExtracting(self, tar):
"""Verify the tarball before extracting it.
Extracting tarballs from untrusted sources is extremely dangerous
as it's trivial to overwrite any part of the filesystem that the
user running this process has access to.
Here, we make sure that the file will extract to somewhere under
the tmp dir, that the file is a directory, regular file or a symlink
only, and that symlinks only resolve to stuff under the tmp dir.
"""
for member in tar.getmembers():
# member is a TarInfo object.
if not (member.isreg() or member.issym() or member.isdir()):
raise CustomUploadTarballInvalidFileType(
self.tarfile_path, member.name)
# Append os.sep to stop attacks like /var/tmp/../tmpBOGUS
# This is unlikely since someone would need to guess what
# mkdtemp returned, but still ...
tmpdir_with_sep = self.tmpdir + os.sep
member_path = os.path.join(self.tmpdir, member.name)
member_realpath = os.path.realpath(member_path)
# The path can either be the tmpdir (without a trailing
# separator) or have the tmpdir plus a trailing separator
# as a prefix.
if (member_realpath != self.tmpdir and
not member_realpath.startswith(tmpdir_with_sep)):
raise CustomUploadTarballBadFile(
self.tarfile_path, member.name)
if member.issym():
# This is a bit tricky. We need to take the dirname of
# the link's name which is where the link's target is
# relative to, and prepend the extraction directory to
# get an absolute path for the link target.
rel_link_file_location = os.path.dirname(member.name)
abs_link_file_location = os.path.join(
self.tmpdir, rel_link_file_location)
target_path = os.path.join(
abs_link_file_location, member.linkname)
target_realpath = os.path.realpath(target_path)
# The same rules apply here as for member_realpath
# above.
if (target_realpath != self.tmpdir and
not target_realpath.startswith(tmpdir_with_sep)):
raise CustomUploadTarballBadSymLink(
self.tarfile_path, member.name, member.linkname)
return True
def extract(self):
"""Extract the custom upload to a temporary directory."""
assert self.tmpdir is None, "Have already extracted tarfile"
self.tmpdir = tempfile.mkdtemp(prefix='customupload_')
try:
tar = tarfile.open(self.tarfile_path)
self.verifyBeforeExtracting(tar)
tar.ignore_zeros = True
try:
for tarinfo in tar:
tar.extract(tarinfo, self.tmpdir)
finally:
tar.close()
except tarfile.TarError, exc:
raise CustomUploadTarballTarError(self.tarfile_path, exc)
def shouldInstall(self, filename):
"""Returns True if the given filename should be installed."""
raise NotImplementedError
def _buildInstallPaths(self, basename, dirname):
"""Build and return paths used to install files.
Return a triple containing: (sourcepath, basepath, destpath)
Where:
* sourcepath is the absolute path to the extracted location.
* basepath is the relative path inside the target location.
* destpath is the absolute path to the target location.
"""
sourcepath = os.path.join(dirname, basename)
assert sourcepath.startswith(self.tmpdir), (
"Source path must refer to the extracted location.")
basepath = sourcepath[len(self.tmpdir):].lstrip(os.path.sep)
destpath = os.path.join(self.targetdir, basepath)
return sourcepath, basepath, destpath
def ensurePath(self, path):
"""Ensure the parent directory exists."""
parentdir = os.path.dirname(path)
if not os.path.isdir(parentdir):
os.makedirs(parentdir, 0755)
def installFiles(self):
"""Install the files from the custom upload to the archive."""
assert self.tmpdir is not None, "Must extract tarfile first"
extracted = False
for dirpath, dirnames, filenames in os.walk(self.tmpdir):
# Create symbolic links to directories.
for dirname in dirnames:
sourcepath, basepath, destpath = self._buildInstallPaths(
dirname, dirpath)
if not self.shouldInstall(basepath):
continue
self.ensurePath(destpath)
# Also, ensure that the process has the expected umask.
old_mask = os.umask(0)
try:
if old_mask != 022:
raise CustomUploadBadUmask(022, old_mask)
finally:
os.umask(old_mask)
if os.path.islink(sourcepath):
os.symlink(os.readlink(sourcepath), destpath)
# XXX cprov 2007-03-27: We don't want to create empty
# directories, some custom formats rely on this, DDTP,
# for instance. We may end up with broken links
# but that's more an uploader fault than anything else.
# Create/Copy files.
for filename in filenames:
sourcepath, basepath, destpath = self._buildInstallPaths(
filename, dirpath)
if not self.shouldInstall(basepath):
continue
self.ensurePath(destpath)
# Remove any previous file, to avoid hard link problems
if os.path.exists(destpath):
os.remove(destpath)
# Copy the file or symlink
if os.path.islink(sourcepath):
os.symlink(os.readlink(sourcepath), destpath)
else:
shutil.copy(sourcepath, destpath)
os.chmod(destpath, 0644)
extracted = True
if not extracted:
raise CustomUploadTarballInvalidTarfile(
self.tarfile_path, self.targetdir)
def fixCurrentSymlink(self):
"""Update the 'current' symlink and prune old entries.
The 'current' symbolic link will point to the latest version present
in 'targetdir' and only the latest 3 valid entries will be kept.
Entries named as invalid versions, for instance 'alpha-X', will be
ignored and left alone. That's because they were probably copied
manually into this location, they should remain in place.
See `DebVersion` for more information about version validation.
"""
# Get an appropriately-sorted list of the valid installer directories
# now present in the target. Deliberately skip 'broken' versions
# because they can't be sorted anyway.
versions = []
for inst in os.listdir(self.targetdir):
# Skip the symlink.
if inst == 'current':
continue
# Skip broken versions.
try:
make_version(inst)
except VersionError:
continue
# Append the valid versions to the list.
versions.append(inst)
versions.sort(key=make_version, reverse=True)
# Make sure the 'current' symlink points to the most recent version
# The most recent version is in versions[0]
current = os.path.join(self.targetdir, 'current')
os.symlink(versions[0], '%s.new' % current)
os.rename('%s.new' % current, current)
# There may be some other unpacked installer directories in
# the target already. We only keep the three with the highest
# version (plus the one we just extracted, if for some reason
# it's lower).
for oldversion in versions[3:]:
if oldversion != self.version:
shutil.rmtree(os.path.join(self.targetdir, oldversion))
def cleanup(self):
"""Clean up the temporary directory"""
if self.tmpdir is not None:
shutil.rmtree(self.tmpdir, ignore_errors=True)
self.tmpdir = None
|