-
Notifications
You must be signed in to change notification settings - Fork 52
/
build.py
executable file
·311 lines (253 loc) · 10.4 KB
/
build.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
import sys
import distutils.spawn
import logging
import zipfile
import subprocess
import shutil
import uImage
import SquashFS
import importlib
from configs.config import *
class DahuaBuilder():
DEPENDENCIES = ["sudo", "mkimage"]
def __init__(self, config, debug):
self.Config = config
self.Debug = debug
self.Logger = logging.getLogger(__class__.__name__)
if self.Debug:
self.Logger.setLevel(logging.DEBUG)
else:
self.Logger.setLevel(logging.INFO)
self.Source = None
self.BuildDir = None
self.ZipFileList = None
self.DestFile = None
self.ZipFile = None
self.DahuaFiles = self.Config.DAHUA_FILES
def CheckDependencies(self):
Ret = 0
for dependency in self.DEPENDENCIES:
if self.CheckDependency(dependency):
Ret = 1
return Ret
def CheckDependency(self, dependency):
if not distutils.spawn.find_executable(dependency):
self.Logger.critical("Missing dependency: '%s'", dependency)
return 1
def Build(self, source):
self.Source = os.path.abspath(source)
# Check if all required files and directories exist
self.Logger.info("Checking required files/directories.")
for Key, Value in self.DahuaFiles.items():
Passed = True
if Value["type"] & DAHUA_TYPE.Plain:
if Value["type"] & DAHUA_TYPE.uImage:
Path = os.path.join(self.Source, Key + ".raw")
else:
Path = os.path.join(self.Source, Key)
if not os.path.isfile(Path):
if Value["required"]:
self.Logger.error("Could not find required file: '%s'", Key)
raise Exception("Missing requirement!")
Passed = False
if Value["type"] & DAHUA_TYPE.uImage:
if not os.path.isfile(os.path.join(self.Source, Key + ".uImage")):
if Value["required"]:
self.Logger.error("Could not find required '.uImage' file for file: '%s'", Key)
raise Exception("Missing requirement!")
Passed = False
if Value["type"] & DAHUA_TYPE.SquashFS:
if not os.path.isdir(os.path.join(self.Source, Key + ".extracted")):
if Value["required"]:
self.Logger.error("Could not find required '.extracted' directory for file: '%s'", Key)
raise Exception("Missing requirement!")
Passed = False
if not os.path.isfile(os.path.join(self.Source, Key + ".raw")):
if Value["required"]:
self.Logger.error("Could not find required '.raw' file for file: '%s'", Key)
raise Exception("Missing requirement!")
Passed = False
Value["pass"] = Passed
if Passed:
self.Logger.debug("Requirements for '%s' were met.", Key)
else:
self.Logger.debug("Requirements for '%s' were NOT met.", Key)
# Check if build directory exists in source dir
self.BuildDir = os.path.join(self.Source, "build")
if os.path.isdir(self.BuildDir):
self.Logger.info("Build directory already exists, deleting.")
shutil.rmtree(self.BuildDir)
# Create build dir
self.Logger.info("Creating 'build' directory.")
os.mkdir(self.BuildDir)
self.ZipFileList = []
#
self.Logger.info("Starting build process.")
for Key, Value in self.DahuaFiles.items():
if not Value["pass"]:
self.Logger.debug("Skipping '%s'.", Key)
continue
self.Logger.info("Processing '%s'.", Key)
if Value["type"] & DAHUA_TYPE.Plain:
if Value["type"] & DAHUA_TYPE.uImage:
OrigPath = os.path.join(self.Source, Key + ".raw")
DestPath = os.path.join(self.BuildDir, Key + ".raw")
shutil.copyfile(OrigPath, DestPath)
else:
OrigPath = os.path.join(self.Source, Key)
DestPath = os.path.join(self.BuildDir, Key)
shutil.copyfile(OrigPath, DestPath)
self.Logger.debug("Adding '%s' to zip file list.", Key)
self.ZipFileList.append((DestPath, Key))
if Value["type"] & DAHUA_TYPE.SquashFS:
if self.Handle_SquashFS(Key) != 0:
self.Logger.error("'SquashFS' handler returned non-zero return value for file: '%s'", Key)
raise Exception("Handler returned non-zero return value!")
if Value["type"] & DAHUA_TYPE.CramFS:
if self.Handle_CramFS(Key) != 0:
self.Logger.error("'CramFS' handler returned non-zero return value for file: '%s'", Key)
raise Exception("Handler returned non-zero return value!")
if Value["type"] & DAHUA_TYPE.uImage:
if self.Handle_uImage(Key) != 0:
self.Logger.error("'uImage' handler returned non-zero return value for file: '%s'", Key)
raise Exception("Handler returned non-zero return value!")
if "size" in Value:
size = Value["size"]
if Value["type"] & DAHUA_TYPE.uImage:
size += uImage.HEADER_SIZE
if os.path.getsize(self.ZipFileList[-1][0]) > size:
self.Logger.error("Generated file '%s' exceedes maximum allowed filesize!", Key)
raise Exception("File exceeds maximum allowed filesize!")
DestPath = os.path.join(self.BuildDir, os.path.basename(self.Source).rstrip(".extracted").rstrip(".bin") + ".bin")
self.DestFile = open(DestPath, "wb")
self.Logger.info("Building compressed firmware image.")
self.ZipFile = zipfile.ZipFile(self.DestFile, mode='w', compression=zipfile.ZIP_DEFLATED)
for Item in self.ZipFileList:
self.Logger.debug("Writing '%s' as '%s' to zip file.", Item[0], Item[1])
self.ZipFile.write(Item[0], Item[1])
self.ZipFile.close()
self.ZipFile = None
# Write DH header
self.Logger.debug("Patching zip header from 'PK' to 'DH'.")
self.DestFile.seek(0)
self.DestFile.write(b"DH")
self.DestFile.close()
self.DestFile = None
def Handle_uImage(self, Key):
OrigPath = os.path.join(self.Source, Key + ".uImage")
DestPath = os.path.join(self.BuildDir, Key)
DataPath = os.path.join(self.BuildDir, Key + ".raw")
# Read uImage header of the original file.
OrigFile = open(OrigPath, "rb")
Header = uImage.parseHeader(OrigFile)
OrigFile.close()
if Header["magic"] != uImage.HEADER_MAGIC:
OrigFile.close()
self.Logger.error("Invalid uImage magic number!")
return 1
Arch = uImage.archType[Header["arch"]][1]
OS = uImage.osType[Header["osType"]][1]
ImageType = uImage.imageType[Header["imageType"]][1]
Compression = uImage.compressType[Header["compression"]][1]
LoadAddress = str(hex(Header["loadAddr"]))[2:]
EntryPoint = str(hex(Header["entryAddr"]))[2:]
Name = Header["name"].decode("ascii", errors="ignore").rstrip('\0')
if self.Debug:
self.Logger.debug(' '.join(["mkimage", "-A", Arch, "-O", OS, "-T", ImageType, "-C", Compression,
"-a", LoadAddress, "-e", EntryPoint, "-n", Name, "-d", DataPath, DestPath]))
Result = subprocess.call(["mkimage", "-A", Arch, "-O", OS, "-T", ImageType, "-C", Compression,
"-a", LoadAddress, "-e", EntryPoint, "-n", Name, "-d", DataPath, DestPath])
self.Logger.debug("Adding '%s' to zip file list.", Key)
self.ZipFileList.append((DestPath, Key))
return Result
def Handle_SquashFS(self, Key):
ExtractedDir = os.path.join(self.Source, Key + ".extracted")
OrigPath = os.path.join(self.Source, Key + ".raw")
DestPath = os.path.join(self.BuildDir, Key + ".raw")
# Read SquashFS header to figure out compression and blocksize of the original file.
OrigFile = open(OrigPath, "rb")
Header = SquashFS.parseHeader(OrigFile)
OrigFile.close()
if Header["s_magic"] != SquashFS.HEADER_MAGIC:
OrigFile.close()
self.Logger.error("Invalid SquashFS magic number!")
return 1
Version = "" if Header["s_major"] == 4 else str(Header["s_major"])
Binary = "mksquashfs" + Version
if self.CheckDependency(Binary):
return 1
ConOpts = SquashFS.buildConOpts(Header)
# Need root to access all files.
if self.Debug:
self.Logger.debug(' '.join(["sudo", Binary, ExtractedDir, DestPath] + ConOpts))
Result = subprocess.call(["sudo", Binary, ExtractedDir, DestPath] + ConOpts)
else:
Result = subprocess.call(["sudo", Binary, ExtractedDir, DestPath] + ConOpts, stdout=subprocess.DEVNULL)
return Result
def Handle_CramFS(self, Key):
ExtractedDir = os.path.join(self.Source, Key + ".extracted")
OrigPath = os.path.join(self.Source, Key + ".raw")
DestPath = os.path.join(self.BuildDir, Key + ".raw")
Binary = "mkcramfs"
if self.CheckDependency(Binary):
return 1
# Need root to access all files.
if self.Debug:
self.Logger.debug(' '.join(["sudo", Binary, ExtractedDir, DestPath]))
Result = subprocess.call(["sudo", Binary, ExtractedDir, DestPath])
else:
Result = subprocess.call(["sudo", Binary, ExtractedDir, DestPath], stdout=subprocess.DEVNULL)
return Result
if __name__ == "__main__":
logging.basicConfig(format="%(levelname)s\t%(message)s")
logging.addLevelName(logging.DEBUG, "\033[1;33m%s\033[1;0m" % logging.getLevelName(logging.DEBUG))
logging.addLevelName(logging.INFO, "\033[1;32m%s\033[1;0m" % logging.getLevelName(logging.INFO))
logging.addLevelName(logging.WARNING, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
logging.addLevelName(logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))
logging.addLevelName(logging.CRITICAL, "\033[5m\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.CRITICAL))
parser = argparse.ArgumentParser(description="Build Dahua firmware images.")
parser.add_argument("-v", "--verbose", action="store_true", help="Turn on verbose (debugging) output")
parser.add_argument("-c", "--config", default="auto", help="Configuration to use. (Default: auto)")
parser.add_argument("source", help="Source Directory (of previously extracted firmware image)")
args = parser.parse_args()
Logger = logging.getLogger("main")
if args.verbose:
Logger.setLevel(logging.DEBUG)
else:
Logger.setLevel(logging.INFO)
if not os.path.isdir(args.source):
Logger.error("No such directory: '%s'", args.source)
sys.exit(1)
Found = None
if args.config == "auto":
Name = os.path.basename(os.path.abspath(args.source))
for Config in DAHUA_CONFIGS:
if Config in Name:
Logger.warn("Autodetected config: %s", Config)
Found = Config
break
if not Found:
Logger.error("Could not autodetect config!")
else:
ArgConfig = args.config.lower()
for Config in DAHUA_CONFIGS:
if Config.lower() == ArgConfig:
Logger.warn("Found config: %s", Config)
Found = Config
break
if not Found:
Logger.error("Invalid config specified! (Add to configs/config.py DAHUA_CONFIGS if you made a new one)")
if not Found:
Logger.info("Please use -c to select the correct config from the following list:")
for Config in DAHUA_CONFIGS:
Logger.info("\t" + Config)
sys.exit(1)
Config = importlib.import_module("configs." + Found)
builder = DahuaBuilder(Config, args.verbose)
if builder.CheckDependencies():
sys.exit(1)
builder.Build(args.source)