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
|
#!/usr/bin/python
#
# 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 2 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 Library 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.
#
# Copyright 2007 Red Hat, Inc. -- Jeremy Katz <katzj@redhat.com>
# Based on genprestometadata.py which was based on genmetadata.py
# Copyright 2007 Jonathan Dieter, Copyright 2004 Duke University
import os, sys, string
import optparse
import gzip
import rpm
import types
import sha
import struct
import libxml2
__version__ = '0.3.0'
class MDError(Exception):
pass
def getFileList(directory, ext):
extlen = len(ext)
def extension_visitor(arg, dirname, names):
for fn in names:
if os.path.isdir(fn):
continue
elif string.lower(fn[-extlen:]) == '%s' % (ext):
reldir = os.path.basename(dirname)
if reldir == os.path.basename(directory):
reldir = ""
arg.append(os.path.join(reldir,fn))
rpmlist = []
startdir = os.path.join(directory)
os.path.walk(startdir, extension_visitor, rpmlist)
return rpmlist
def generateXML(doc, node, drpmObj, sumtype, pkgDeltas):
"""takes an xml doc object and a package metadata entry node, populates a
package node with the md information"""
name = drpmObj.tagByName('name')
arch = drpmObj.tagByName('arch')
epoch = str(drpmObj.epoch())
ver = str(drpmObj.tagByName('version'))
rel = str(drpmObj.tagByName('release'))
if not pkgDeltas.has_key('%s-%s:%s-%s.%s' % (name, epoch, ver, rel, arch)):
pkgNode = node.newChild(None, "newpackage", None)
pkgNode.newProp('name', name)
pkgNode.newProp('epoch', epoch)
pkgNode.newProp('version', ver)
pkgNode.newProp('release', rel)
pkgNode.newProp('arch', arch)
pkgDeltas['%s-%s:%s-%s.%s' % (name, epoch, ver, rel, arch)] = pkgNode
else:
pkgNode = pkgDeltas['%s-%s:%s-%s.%s' % (name, epoch, ver, rel, arch)]
delta = pkgNode.newChild(None, "delta", None)
delta.newChild(None, 'filename', drpmObj.relativepath)
delta.newChild(None, 'sequence', "%s-%s" %(drpmObj.oldnevrstring, drpmObj.sequence))
delta.newChild(None, 'size', str(drpmObj.size))
sum = delta.newChild(None, 'checksum', drpmObj.pkgid)
sum.newProp('type', 'sha')
(oldname, oldepoch, oldver, oldrel) = drpmObj.oldnevr
delta.newProp('oldepoch', oldepoch)
delta.newProp('oldversion', oldver)
delta.newProp('oldrelease', oldrel)
def byteranges(file):
"""takes an rpm file or fileobject and returns byteranges for location of the header"""
opened_here = 0
if type(file) is not types.StringType:
fo = file
else:
opened_here = 1
fo = open(file, 'r')
#read in past lead and first 8 bytes of sig header
fo.seek(104)
# 104 bytes in
binindex = fo.read(4)
# 108 bytes in
(sigindex, ) = struct.unpack('>I', binindex)
bindata = fo.read(4)
# 112 bytes in
(sigdata, ) = struct.unpack('>I', bindata)
# each index is 4 32bit segments - so each is 16 bytes
sigindexsize = sigindex * 16
sigsize = sigdata + sigindexsize
# we have to round off to the next 8 byte boundary
disttoboundary = (sigsize % 8)
if disttoboundary != 0:
disttoboundary = 8 - disttoboundary
# 112 bytes - 96 == lead, 8 = magic and reserved, 8 == sig header data
hdrstart = 112 + sigsize + disttoboundary
fo.seek(hdrstart) # go to the start of the header
fo.seek(8,1) # read past the magic number and reserved bytes
binindex = fo.read(4)
(hdrindex, ) = struct.unpack('>I', binindex)
bindata = fo.read(4)
(hdrdata, ) = struct.unpack('>I', bindata)
# each index is 4 32bit segments - so each is 16 bytes
hdrindexsize = hdrindex * 16
# add 16 to the hdrsize to account for the 16 bytes of misc data b/t the
# end of the sig and the header.
hdrsize = hdrdata + hdrindexsize + 16
# header end is hdrstart + hdrsize
hdrend = hdrstart + hdrsize
if opened_here:
fo.close()
del fo
return (hdrstart, hdrend)
class DrpmMetaData:
"""each drpm is one object, you pass it an rpm file
it opens the file, and pulls the information out in bite-sized chunks :)
"""
mode_cache = {}
def __init__(self, ts, basedir, filename):
try:
stats = os.stat(os.path.join(basedir, filename))
self.size = stats[6]
self.mtime = stats[8]
del stats
except OSError, e:
raise MDError, "Error Stat'ing file %s %s" % (basedir, filename)
self.relativepath = filename
fd = os.open(os.path.join(basedir, filename), os.O_RDONLY)
self.hdr = ts.hdrFromFdno(fd)
os.lseek(fd, 0, 0)
fo = os.fdopen(fd, 'rb')
self.pkgid = self.getChecksum("sha", fo)
fo.seek(0)
(start, end) = byteranges(fo)
fo.seek(end)
self._getOldInfo(fo)
del fo
del fd
def arch(self):
if self.tagByName('sourcepackage') == 1:
return 'src'
else:
return self.tagByName('arch')
def _stringToNEVR(self, string):
i = string.rfind("-", 0, string.rfind("-")-1)
name = string[:i]
(epoch, ver, rel) = self._stringToVersion(string[i+1:])
return (name, epoch, ver, rel)
def _getLength(self, in_data):
length = 0
for val in in_data:
length = length * 256
length += ord(val)
return length
def _getOldInfo(self, fo):
try:
compobj = gzip.GzipFile("", "rb", 9, fo)
except:
raise zlibError("Data not stored in gzip format")
if compobj.read(4)[:3] != "DLT":
raise Exception("Not a deltarpm")
nevr_length = self._getLength(compobj.read(4))
nevr = compobj.read(nevr_length).strip("\x00")
seq_length = self._getLength(compobj.read(4))
seq = compobj.read(seq_length)
hex_seq = ""
for char in seq:
hex_seq += str("%02x" % ord(char))
self.oldnevrstring = nevr
self.oldnevr = self._stringToNEVR(nevr)
self.sequence = hex_seq
compobj.close()
def _stringToVersion(self, strng):
i = strng.find(':')
if i != -1:
epoch = strng[:i]
else:
epoch = '0'
j = strng.find('-')
if j != -1:
if strng[i + 1:j] == '':
version = None
else:
version = strng[i + 1:j]
release = strng[j + 1:]
else:
if strng[i + 1:] == '':
version = None
else:
version = strng[i + 1:]
release = None
return (epoch, version, release)
def tagByName(self, tag):
data = self.hdr[tag]
if type(data) is types.ListType:
if len(data) > 0:
return data[0]
else:
return ''
else:
return data
def epoch(self):
if self.hdr['epoch'] is None:
return 0
else:
return self.tagByName('epoch')
def getChecksum(self, sumtype, file, CHUNK=2**16):
"""takes filename, hand back Checksum of it
sumtype = md5 or sha
filename = /path/to/file
CHUNK=65536 by default"""
# chunking brazenly lifted from Ryan Tomayko
opened_here = 0
try:
if type(file) is not types.StringType:
fo = file # assume it's a file-like-object
else:
opened_here = 1
fo = open(file, 'rb', CHUNK)
if sumtype == 'md5':
sum = md5.new()
elif sumtype == 'sha':
sum = sha.new()
else:
raise MDError, 'Error Checksumming file, wrong checksum type %s' % sumtype
chunk = fo.read
while chunk:
chunk = fo.read(CHUNK)
sum.update(chunk)
if opened_here:
fo.close()
del fo
return sum.hexdigest()
except Exception, e:
print e
raise MDError, 'Error opening file for checksum: %s' % file
def writePrestoData(deltadir, outputdir):
files = getFileList(deltadir, ".drpm")
doc = libxml2.newDoc("1.0")
root = doc.newChild(None, "prestodelta", None)
deltas = {}
ts = rpm.TransactionSet()
ts.setVSFlags(-1)
for f in files:
drpmobj = DrpmMetaData(ts, deltadir, f)
generateXML(doc, root, drpmobj, "sha", deltas)
prestofile = open("%s/prestodelta.xml" %(outputdir,), "w")
prestofile.write('<?xml version="1.0" encoding="UTF-8"?>\n')
prestofile.write(root.serialize("UTF-8", True))
prestofile.close()
def usage():
print >> sys.stderr, "Usage: %s <deltadir> <outputdir>" %(sys.argv[0])
def main(args):
if len(args) == 0:
usage()
sys.exit(1)
deltadir = args[0]
if len(args) > 1:
outputdir = args[1]
else:
outputdir = "%s/repodata" %(deltadir,)
if not os.path.isdir(deltadir):
print >> sys.stderr, "Delta directory must exist."
sys.exit(1)
if not os.access(outputdir, os.W_OK):
print >> sys.stderr, "Output directory must be writable."
sys.exit(1)
writePrestoData(deltadir, outputdir)
if __name__ == "__main__":
main(sys.argv[1:])
|