pkg-stats 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. #!/usr/bin/env python3
  2. # Copyright (C) 2009 by Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
  3. # Copyright (C) 2022 by Sen Hastings <sen@phobosdpl.com>
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. # General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. import aiohttp
  19. import argparse
  20. import asyncio
  21. import datetime
  22. import fnmatch
  23. import os
  24. from collections import defaultdict, namedtuple
  25. import re
  26. import subprocess
  27. import json
  28. import sys
  29. brpath = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", ".."))
  30. sys.path.append(os.path.join(brpath, "utils"))
  31. from getdeveloperlib import parse_developers # noqa: E402
  32. INFRA_RE = re.compile(r"\$\(eval \$\(([a-z-]*)-package\)\)")
  33. URL_RE = re.compile(r"\s*https?://\S*\s*$")
  34. RM_API_STATUS_ERROR = 1
  35. RM_API_STATUS_FOUND_BY_DISTRO = 2
  36. RM_API_STATUS_FOUND_BY_PATTERN = 3
  37. RM_API_STATUS_NOT_FOUND = 4
  38. class Defconfig:
  39. def __init__(self, name, path):
  40. self.name = name
  41. self.path = path
  42. self.developers = None
  43. def set_developers(self, developers):
  44. """
  45. Fills in the .developers field
  46. """
  47. self.developers = [
  48. developer.name
  49. for developer in developers
  50. if developer.hasfile(self.path)
  51. ]
  52. def get_defconfig_list():
  53. """
  54. Builds the list of Buildroot defconfigs, returning a list of Defconfig
  55. objects.
  56. """
  57. return [
  58. Defconfig(name[:-len('_defconfig')], os.path.join('configs', name))
  59. for name in os.listdir(os.path.join(brpath, 'configs'))
  60. if name.endswith('_defconfig')
  61. ]
  62. Br2Tree = namedtuple("Br2Tree", ["name", "path"])
  63. def get_trees():
  64. raw_variables = subprocess.check_output(["make", "--no-print-directory", "-s",
  65. "BR2_HAVE_DOT_CONFIG=y", "printvars",
  66. "VARS=BR2_EXTERNAL_NAMES BR2_EXTERNAL_%_PATH"])
  67. variables = dict(line.split("=") for line in raw_variables.decode().split("\n") if line)
  68. variables["BR2_EXTERNAL_BUILDROOT_PATH"] = brpath
  69. externals = ["BUILDROOT", *variables["BR2_EXTERNAL_NAMES"].split()]
  70. return [Br2Tree(name, os.path.normpath(variables[f"BR2_EXTERNAL_{name}_PATH"])) for name in externals]
  71. class Package:
  72. all_licenses = dict()
  73. all_license_files = list()
  74. all_versions = dict()
  75. all_ignored_cves = dict()
  76. all_cpeids = dict()
  77. # This is the list of all possible checks. Add new checks to this list so
  78. # a tool that post-processes the json output knows the checks before
  79. # iterating over the packages.
  80. status_checks = ['cve', 'developers', 'hash', 'license',
  81. 'license-files', 'patches', 'pkg-check', 'url', 'version']
  82. def __init__(self, tree, name, path):
  83. self.tree = tree.name
  84. self.tree_path = tree.path
  85. self.name = name
  86. self.path = path
  87. self.pkg_path = os.path.dirname(path)
  88. # Contains a list of tuple (type, infra), such as ("target",
  89. # "autotools"). When pkg-stats is run without -c, it contains
  90. # the list of all infra/type supported by the package. When
  91. # pkg-stats is run with -c, it contains the list of infra/type
  92. # used by the current configuration.
  93. self.infras = None
  94. self.license = None
  95. self.has_license = False
  96. self.has_license_files = False
  97. self.has_hash = False
  98. self.patch_files = []
  99. self.warnings = 0
  100. self.current_version = None
  101. self.url = None
  102. self.url_worker = None
  103. self.cpeid = None
  104. self.cves = list()
  105. self.ignored_cves = list()
  106. self.unsure_cves = list()
  107. self.latest_version = {'status': RM_API_STATUS_ERROR, 'version': None, 'id': None}
  108. self.status = {}
  109. def pkgvar(self):
  110. return self.name.upper().replace("-", "_")
  111. @property
  112. def pkgdir(self):
  113. return os.path.join(self.tree_path, self.pkg_path)
  114. @property
  115. def pkgfile(self):
  116. return os.path.join(self.tree_path, self.path)
  117. @property
  118. def hashpath(self):
  119. return self.pkgfile.replace(".mk", ".hash")
  120. def set_url(self):
  121. """
  122. Fills in the .url field
  123. """
  124. self.status['url'] = ("warning", "no Config.in")
  125. for filename in os.listdir(self.pkgdir):
  126. if fnmatch.fnmatch(filename, 'Config.*'):
  127. fp = open(os.path.join(self.pkgdir, filename), "r")
  128. for config_line in fp:
  129. if URL_RE.match(config_line):
  130. self.url = config_line.strip()
  131. self.status['url'] = ("ok", "found")
  132. fp.close()
  133. return
  134. self.status['url'] = ("error", "missing")
  135. fp.close()
  136. @property
  137. def patch_count(self):
  138. return len(self.patch_files)
  139. @property
  140. def has_valid_infra(self):
  141. if self.infras is None:
  142. return False
  143. return len(self.infras) > 0
  144. @property
  145. def is_actual_package(self):
  146. try:
  147. if not self.has_valid_infra:
  148. return False
  149. if self.infras[0][1] == 'virtual':
  150. return False
  151. except IndexError:
  152. return False
  153. return True
  154. def set_infra(self, show_info_js):
  155. """
  156. Fills in the .infras field
  157. """
  158. # If we're running pkg-stats for a given Buildroot
  159. # configuration, keep only the type/infra that applies
  160. if show_info_js:
  161. keep_host = "host-%s" % self.name in show_info_js
  162. keep_target = self.name in show_info_js
  163. # Otherwise, keep all
  164. else:
  165. keep_host = True
  166. keep_target = True
  167. self.infras = list()
  168. with open(self.pkgfile, 'r') as f:
  169. lines = f.readlines()
  170. for line in lines:
  171. match = INFRA_RE.match(line)
  172. if not match:
  173. continue
  174. infra = match.group(1)
  175. if infra.startswith("host-") and keep_host:
  176. self.infras.append(("host", infra[5:]))
  177. elif keep_target:
  178. self.infras.append(("target", infra))
  179. def set_license(self):
  180. """
  181. Fills in the .status['license'] and .status['license-files'] fields
  182. """
  183. if not self.is_actual_package:
  184. self.status['license'] = ("na", "no valid package infra")
  185. self.status['license-files'] = ("na", "no valid package infra")
  186. return
  187. var = self.pkgvar()
  188. self.status['license'] = ("error", "missing")
  189. self.status['license-files'] = ("error", "missing")
  190. if var in self.all_licenses:
  191. self.license = self.all_licenses[var]
  192. self.status['license'] = ("ok", "found")
  193. if var in self.all_license_files:
  194. self.status['license-files'] = ("ok", "found")
  195. def set_hash_info(self):
  196. """
  197. Fills in the .status['hash'] field
  198. """
  199. if not self.is_actual_package:
  200. self.status['hash'] = ("na", "no valid package infra")
  201. self.status['hash-license'] = ("na", "no valid package infra")
  202. return
  203. if os.path.exists(self.hashpath):
  204. self.status['hash'] = ("ok", "found")
  205. else:
  206. self.status['hash'] = ("error", "missing")
  207. def set_patch_count(self):
  208. """
  209. Fills in the .patch_count, .patch_files and .status['patches'] fields
  210. """
  211. if not self.is_actual_package:
  212. self.status['patches'] = ("na", "no valid package infra")
  213. return
  214. for subdir, _, _ in os.walk(self.pkgdir):
  215. self.patch_files = fnmatch.filter(os.listdir(subdir), '*.patch')
  216. if self.patch_count == 0:
  217. self.status['patches'] = ("ok", "no patches")
  218. elif self.patch_count < 5:
  219. self.status['patches'] = ("warning", "some patches")
  220. else:
  221. self.status['patches'] = ("error", "lots of patches")
  222. def set_current_version(self):
  223. """
  224. Fills in the .current_version field
  225. """
  226. var = self.pkgvar()
  227. if var in self.all_versions:
  228. self.current_version = self.all_versions[var]
  229. def set_cpeid(self):
  230. """
  231. Fills in the .cpeid field
  232. """
  233. var = self.pkgvar()
  234. if not self.is_actual_package:
  235. self.status['cpe'] = ("na", "N/A - virtual pkg")
  236. return
  237. if not self.current_version:
  238. self.status['cpe'] = ("na", "no version information available")
  239. return
  240. if var in self.all_cpeids:
  241. self.cpeid = self.all_cpeids[var]
  242. self.status['cpe'] = ("ok", "(not checked against CPE dictionary)")
  243. else:
  244. self.status['cpe'] = ("error", "no verified CPE identifier")
  245. def set_check_package_warnings(self):
  246. """
  247. Fills in the .warnings and .status['pkg-check'] fields
  248. """
  249. cmd = [os.path.join(brpath, "utils/check-package")]
  250. self.status['pkg-check'] = ("error", "Missing")
  251. for root, dirs, files in os.walk(self.pkgdir):
  252. for f in files:
  253. cmd.append(os.path.join(root, f))
  254. o = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[1]
  255. lines = o.splitlines()
  256. for line in lines:
  257. m = re.match("^([0-9]*) warnings generated", line.decode())
  258. if m:
  259. self.warnings = int(m.group(1))
  260. if self.warnings == 0:
  261. self.status['pkg-check'] = ("ok", "no warnings")
  262. else:
  263. self.status['pkg-check'] = ("error", "{} warnings".format(self.warnings))
  264. return
  265. def set_ignored_cves(self):
  266. """
  267. Give the list of CVEs ignored by the package
  268. """
  269. self.ignored_cves = list(self.all_ignored_cves.get(self.pkgvar(), []))
  270. def set_developers(self, developers):
  271. """
  272. Fills in the .developers and .status['developers'] field
  273. """
  274. self.developers = [
  275. dev.name
  276. for dev in developers
  277. if dev.hasfile(self.path)
  278. ]
  279. if self.developers:
  280. self.status['developers'] = ("ok", "{} developers".format(len(self.developers)))
  281. else:
  282. self.status['developers'] = ("warning", "no developers")
  283. def is_status_ok(self, name):
  284. return name in self.status and self.status[name][0] == 'ok'
  285. def is_status_error(self, name):
  286. return name in self.status and self.status[name][0] == 'error'
  287. def is_status_na(self, name):
  288. return name in self.status and self.status[name][0] == 'na'
  289. def __eq__(self, other):
  290. return self.path == other.path
  291. def __lt__(self, other):
  292. return self.path < other.path
  293. def __str__(self):
  294. return "%s (path='%s', license='%s', license_files='%s', hash='%s', patches=%d)" % \
  295. (self.name, self.path, self.is_status_ok('license'),
  296. self.is_status_ok('license-files'), self.status['hash'], self.patch_count)
  297. def get_pkglist(trees, npackages, package_list):
  298. """
  299. Builds the list of Buildroot packages, returning a list of Package
  300. objects. Only the .name and .path fields of the Package object are
  301. initialized.
  302. npackages: limit to N packages
  303. package_list: limit to those packages in this list
  304. """
  305. WALK_USEFUL_SUBDIRS = ["boot", "linux", "package", "toolchain"]
  306. WALK_EXCLUDES = ["boot/barebox/barebox.mk",
  307. "boot/common.mk",
  308. "linux/linux-ext-.*.mk",
  309. "package/fftw/fftw.mk",
  310. "package/freescale-imx/freescale-imx.mk",
  311. "package/gcc/gcc.mk",
  312. "package/gstreamer/gstreamer.mk",
  313. "package/gstreamer1/gstreamer1.mk",
  314. "package/gtk2-themes/gtk2-themes.mk",
  315. "package/kf5/kf5.mk",
  316. "package/llvm-project/llvm-project.mk",
  317. "package/matchbox/matchbox.mk",
  318. "package/opengl/opengl.mk",
  319. "package/qt5/qt5.mk",
  320. "package/qt6/qt6.mk",
  321. "package/x11r7/x11r7.mk",
  322. "package/doc-asciidoc.mk",
  323. "package/pkg-.*.mk",
  324. "toolchain/toolchain-external/pkg-toolchain-external.mk",
  325. "toolchain/toolchain-external/toolchain-external.mk",
  326. "toolchain/toolchain.mk",
  327. "toolchain/helpers.mk",
  328. "toolchain/toolchain-wrapper.mk"]
  329. packages = list()
  330. count = 0
  331. for br_tree, root, dirs, files in ((tree, *rdf) for tree in trees for rdf in os.walk(tree.path)):
  332. root = os.path.relpath(root, br_tree.path)
  333. rootdir = root.split("/")
  334. if len(rootdir) < 1:
  335. continue
  336. if rootdir[0] not in WALK_USEFUL_SUBDIRS:
  337. continue
  338. for f in files:
  339. if not f.endswith(".mk"):
  340. continue
  341. # Strip ending ".mk"
  342. pkgname = f[:-3]
  343. if package_list and pkgname not in package_list:
  344. continue
  345. pkgpath = os.path.join(root, f)
  346. skip = False
  347. for exclude in WALK_EXCLUDES:
  348. if re.match(exclude, pkgpath):
  349. skip = True
  350. continue
  351. if skip:
  352. continue
  353. p = Package(br_tree, pkgname, pkgpath)
  354. packages.append(p)
  355. count += 1
  356. if npackages and count == npackages:
  357. return packages
  358. return packages
  359. def get_show_info_js():
  360. cmd = ["make", "--no-print-directory", "show-info"]
  361. return json.loads(subprocess.check_output(cmd))
  362. def package_init_make_info():
  363. # Fetch all variables at once
  364. variables = subprocess.check_output(["make", "--no-print-directory", "-s",
  365. "BR2_HAVE_DOT_CONFIG=y", "printvars",
  366. "VARS=%_LICENSE %_LICENSE_FILES %_VERSION %_IGNORE_CVES %_CPE_ID"])
  367. variable_list = variables.decode().splitlines()
  368. # We process first the host package VERSION, and then the target
  369. # package VERSION. This means that if a package exists in both
  370. # target and host variants, with different values (eg. version
  371. # numbers (unlikely)), we'll report the target one.
  372. variable_list = [x[5:] for x in variable_list if x.startswith("HOST_")] + \
  373. [x for x in variable_list if not x.startswith("HOST_")]
  374. for item in variable_list:
  375. # Get variable name and value
  376. pkgvar, value = item.split("=", maxsplit=1)
  377. # Strip the suffix according to the variable
  378. if pkgvar.endswith("_LICENSE"):
  379. # If value is "unknown", no license details available
  380. if value == "unknown":
  381. continue
  382. pkgvar = pkgvar[:-8]
  383. Package.all_licenses[pkgvar] = value
  384. elif pkgvar.endswith("_LICENSE_FILES"):
  385. if pkgvar.endswith("_MANIFEST_LICENSE_FILES"):
  386. continue
  387. pkgvar = pkgvar[:-14]
  388. Package.all_license_files.append(pkgvar)
  389. elif pkgvar.endswith("_VERSION"):
  390. if pkgvar.endswith("_DL_VERSION"):
  391. continue
  392. pkgvar = pkgvar[:-8]
  393. Package.all_versions[pkgvar] = value
  394. elif pkgvar.endswith("_IGNORE_CVES"):
  395. pkgvar = pkgvar[:-12]
  396. Package.all_ignored_cves[pkgvar] = value.split()
  397. elif pkgvar.endswith("_CPE_ID"):
  398. pkgvar = pkgvar[:-7]
  399. Package.all_cpeids[pkgvar] = value
  400. check_url_count = 0
  401. async def check_url_status(session, pkg, npkgs, retry=True):
  402. global check_url_count
  403. try:
  404. async with session.get(pkg.url) as resp:
  405. if resp.status >= 400:
  406. pkg.status['url'] = ("error", "invalid {}".format(resp.status))
  407. check_url_count += 1
  408. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  409. return
  410. except (aiohttp.ClientError, asyncio.TimeoutError):
  411. if retry:
  412. return await check_url_status(session, pkg, npkgs, retry=False)
  413. else:
  414. pkg.status['url'] = ("error", "invalid (err)")
  415. check_url_count += 1
  416. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  417. return
  418. pkg.status['url'] = ("ok", "valid")
  419. check_url_count += 1
  420. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  421. async def check_package_urls(packages):
  422. tasks = []
  423. connector = aiohttp.TCPConnector(limit_per_host=5)
  424. async with aiohttp.ClientSession(connector=connector, trust_env=True,
  425. timeout=aiohttp.ClientTimeout(total=15)) as sess:
  426. packages = [p for p in packages if p.status['url'][0] == 'ok']
  427. for pkg in packages:
  428. tasks.append(asyncio.ensure_future(check_url_status(sess, pkg, len(packages))))
  429. await asyncio.wait(tasks)
  430. def check_package_latest_version_set_status(pkg, status, version, identifier):
  431. pkg.latest_version = {
  432. "status": status,
  433. "version": version,
  434. "id": identifier,
  435. }
  436. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  437. pkg.status['version'] = ('warning', "Release Monitoring API error")
  438. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  439. pkg.status['version'] = ('warning', "Package not found on Release Monitoring")
  440. if pkg.latest_version['version'] is None:
  441. pkg.status['version'] = ('warning', "No upstream version available on Release Monitoring")
  442. elif pkg.latest_version['version'] != pkg.current_version:
  443. pkg.status['version'] = ('error', "The newer version {} is available upstream".format(pkg.latest_version['version']))
  444. else:
  445. pkg.status['version'] = ('ok', 'up-to-date')
  446. async def check_package_get_latest_version_by_distro(session, pkg, retry=True):
  447. url = "https://release-monitoring.org/api/project/Buildroot/%s" % pkg.name
  448. try:
  449. async with session.get(url) as resp:
  450. if resp.status != 200:
  451. return False
  452. data = await resp.json()
  453. if 'stable_versions' in data and data['stable_versions']:
  454. version = data['stable_versions'][0]
  455. elif 'version' in data:
  456. version = data['version']
  457. else:
  458. version = None
  459. check_package_latest_version_set_status(pkg,
  460. RM_API_STATUS_FOUND_BY_DISTRO,
  461. version,
  462. data['id'])
  463. return True
  464. except (aiohttp.ClientError, asyncio.TimeoutError):
  465. if retry:
  466. return await check_package_get_latest_version_by_distro(session, pkg, retry=False)
  467. else:
  468. return False
  469. async def check_package_get_latest_version_by_guess(session, pkg, retry=True):
  470. url = "https://release-monitoring.org/api/projects/?pattern=%s" % pkg.name
  471. try:
  472. async with session.get(url) as resp:
  473. if resp.status != 200:
  474. return False
  475. data = await resp.json()
  476. # filter projects that have the right name and a version defined
  477. projects = [p for p in data['projects'] if p['name'] == pkg.name and 'stable_versions' in p]
  478. projects.sort(key=lambda x: x['id'])
  479. if len(projects) == 0:
  480. return False
  481. if len(projects[0]['stable_versions']) == 0:
  482. return False
  483. check_package_latest_version_set_status(pkg,
  484. RM_API_STATUS_FOUND_BY_PATTERN,
  485. projects[0]['stable_versions'][0],
  486. projects[0]['id'])
  487. return True
  488. except (aiohttp.ClientError, asyncio.TimeoutError):
  489. if retry:
  490. return await check_package_get_latest_version_by_guess(session, pkg, retry=False)
  491. else:
  492. return False
  493. check_latest_count = 0
  494. async def check_package_latest_version_get(session, pkg, npkgs):
  495. global check_latest_count
  496. if await check_package_get_latest_version_by_distro(session, pkg):
  497. check_latest_count += 1
  498. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  499. return
  500. if await check_package_get_latest_version_by_guess(session, pkg):
  501. check_latest_count += 1
  502. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  503. return
  504. check_package_latest_version_set_status(pkg,
  505. RM_API_STATUS_NOT_FOUND,
  506. None, None)
  507. check_latest_count += 1
  508. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  509. async def check_package_latest_version(packages):
  510. """
  511. Fills in the .latest_version field of all Package objects
  512. This field is a dict and has the following keys:
  513. - status: one of RM_API_STATUS_ERROR,
  514. RM_API_STATUS_FOUND_BY_DISTRO, RM_API_STATUS_FOUND_BY_PATTERN,
  515. RM_API_STATUS_NOT_FOUND
  516. - version: string containing the latest version known by
  517. release-monitoring.org for this package
  518. - id: string containing the id of the project corresponding to this
  519. package, as known by release-monitoring.org
  520. """
  521. for pkg in [p for p in packages if not p.is_actual_package]:
  522. pkg.status['version'] = ("na", "no valid package infra")
  523. tasks = []
  524. connector = aiohttp.TCPConnector(limit_per_host=5)
  525. async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
  526. packages = [p for p in packages if p.is_actual_package]
  527. for pkg in packages:
  528. tasks.append(asyncio.ensure_future(check_package_latest_version_get(sess, pkg, len(packages))))
  529. await asyncio.wait(tasks)
  530. def check_package_cve_affects(cve, cpe_product_pkgs):
  531. for product in cve.affected_products:
  532. if product not in cpe_product_pkgs:
  533. continue
  534. for pkg in cpe_product_pkgs[product]:
  535. cve_status = cve.affects(pkg.name, pkg.current_version, pkg.ignored_cves, pkg.cpeid)
  536. if cve_status == cve.CVE_AFFECTS:
  537. pkg.cves.append(cve.identifier)
  538. elif cve_status == cve.CVE_UNKNOWN:
  539. pkg.unsure_cves.append(cve.identifier)
  540. def check_package_cves(nvd_path, packages):
  541. if not os.path.isdir(nvd_path):
  542. os.makedirs(nvd_path)
  543. cpe_product_pkgs = defaultdict(list)
  544. for pkg in packages:
  545. if not pkg.is_actual_package:
  546. pkg.status['cve'] = ("na", "N/A")
  547. continue
  548. if not pkg.current_version:
  549. pkg.status['cve'] = ("na", "no version information available")
  550. continue
  551. if pkg.cpeid:
  552. cpe_product = cvecheck.cpe_product(pkg.cpeid)
  553. cpe_product_pkgs[cpe_product].append(pkg)
  554. else:
  555. cpe_product_pkgs[pkg.name].append(pkg)
  556. for cve in cvecheck.CVE.read_nvd_dir(nvd_path):
  557. check_package_cve_affects(cve, cpe_product_pkgs)
  558. for pkg in packages:
  559. if 'cve' not in pkg.status:
  560. if pkg.cves or pkg.unsure_cves:
  561. pkg.status['cve'] = ("error", "affected by CVEs")
  562. else:
  563. pkg.status['cve'] = ("ok", "not affected by CVEs")
  564. def calculate_stats(packages):
  565. stats = defaultdict(int)
  566. stats['packages'] = len(packages)
  567. for pkg in packages:
  568. # If packages have multiple infra, take the first one. For the
  569. # vast majority of packages, the target and host infra are the
  570. # same. There are very few packages that use a different infra
  571. # for the host and target variants.
  572. if len(pkg.infras) > 0:
  573. infra = pkg.infras[0][1]
  574. stats["infra-%s" % infra] += 1
  575. else:
  576. stats["infra-unknown"] += 1
  577. if pkg.is_status_ok('license'):
  578. stats["license"] += 1
  579. else:
  580. stats["no-license"] += 1
  581. if pkg.is_status_ok('license-files'):
  582. stats["license-files"] += 1
  583. else:
  584. stats["no-license-files"] += 1
  585. if pkg.is_status_ok('hash'):
  586. stats["hash"] += 1
  587. else:
  588. stats["no-hash"] += 1
  589. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  590. stats["rmo-mapping"] += 1
  591. else:
  592. stats["rmo-no-mapping"] += 1
  593. if not pkg.latest_version['version']:
  594. stats["version-unknown"] += 1
  595. elif pkg.latest_version['version'] == pkg.current_version:
  596. stats["version-uptodate"] += 1
  597. else:
  598. stats["version-not-uptodate"] += 1
  599. stats["patches"] += pkg.patch_count
  600. stats["total-cves"] += len(pkg.cves)
  601. stats["total-unsure-cves"] += len(pkg.unsure_cves)
  602. if len(pkg.cves) != 0:
  603. stats["pkg-cves"] += 1
  604. if len(pkg.unsure_cves) != 0:
  605. stats["pkg-unsure-cves"] += 1
  606. if pkg.cpeid:
  607. stats["cpe-id"] += 1
  608. else:
  609. stats["no-cpe-id"] += 1
  610. return stats
  611. html_header = """
  612. <!DOCTYPE html>
  613. <html lang="en">
  614. <head>
  615. <meta charset="UTF-8">
  616. <meta name="viewport" content="width=device-width, initial-scale=1">
  617. <script>
  618. const triangleUp = String.fromCodePoint(32, 9652);
  619. const triangleDown = String.fromCodePoint(32, 9662);
  620. var lastColumnName = false;
  621. const styleElement = document.createElement('style');
  622. document.head.insertAdjacentElement("afterend", styleElement);
  623. const styleSheet = styleElement.sheet;
  624. addedCSSRules = [
  625. ".collapse{ height: 200px; overflow: hidden scroll;}",
  626. ".see-more{ display: block;}",
  627. ".label:hover,.see-more:hover { cursor: pointer; background: #d2ffc4;}"
  628. ];
  629. addedCSSRules.forEach(rule => styleSheet.insertRule(rule));
  630. function sortGrid(sortLabel){
  631. let i = 0;
  632. let pkgSortArray = [], sortedPkgArray = [], pkgStringSortArray = [], pkgNumSortArray = [];
  633. const git_hash_regex = /[a-f,0-9]/gi;
  634. const columnValues = Array.from(document.getElementsByClassName(sortLabel));
  635. const columnName = document.getElementById(sortLabel);
  636. let lastStyle = document.getElementById("sort-css");
  637. if (lastStyle){
  638. lastStyle.disable = true;
  639. lastStyle.remove();
  640. };
  641. styleElement.id = "sort-css";
  642. document.head.appendChild(styleElement);
  643. const styleSheet = styleElement.sheet;
  644. columnValues.shift();
  645. columnValues.forEach((listing) => {
  646. let sortArr = [];
  647. sortArr[0] = listing.id.replace(sortLabel+"_", "");
  648. if (!listing.innerText){
  649. sortArr[1] = -1;
  650. } else {
  651. sortArr[1] = listing.innerText;
  652. };
  653. pkgSortArray.push(sortArr);
  654. });
  655. pkgSortArray.forEach((listing) => {
  656. if ( listing[1].length >= 39 && listing[1].match(git_hash_regex).length >= 39){
  657. pkgStringSortArray.push(listing);
  658. } else if ( isNaN(parseInt(listing[1], 10)) ){
  659. pkgStringSortArray.push(listing);
  660. } else {
  661. listing[1] = parseFloat(listing[1]);
  662. pkgNumSortArray.push(listing);
  663. };
  664. });
  665. let sortedStringPkgArray = pkgStringSortArray.sort((a, b) => {
  666. if (a[1].toUpperCase() < b[1].toUpperCase()) { return -1; };
  667. if (a[1].toUpperCase() > b[1].toUpperCase()) { return 1; };
  668. return 0;
  669. });
  670. let sortedNumPkgArray = pkgNumSortArray.sort((a, b) => a[1] - b[1]);
  671. if (columnName.lastElementChild.innerText == triangleDown) {
  672. columnName.lastElementChild.innerText = triangleUp;
  673. sortedStringPkgArray.reverse();
  674. sortedNumPkgArray.reverse();
  675. sortedPkgArray = sortedNumPkgArray.concat(sortedStringPkgArray);
  676. } else {
  677. columnName.lastElementChild.innerText = triangleDown;
  678. sortedPkgArray = sortedStringPkgArray.concat(sortedNumPkgArray);
  679. };
  680. if (lastColumnName && lastColumnName != columnName){lastColumnName.lastElementChild.innerText = ""};
  681. lastColumnName = columnName;
  682. sortedPkgArray.unshift(["label"]);
  683. sortedPkgArray.forEach((listing) => {
  684. i++;
  685. let rule = "." + listing[0] + " { grid-row: " + i + "; }";
  686. styleSheet.insertRule(rule);
  687. });
  688. addedCSSRules.forEach(rule => styleSheet.insertRule(rule));
  689. };
  690. function expandField(fieldId){
  691. const field = document.getElementById(fieldId);
  692. const fieldText = field.firstElementChild.innerText;
  693. const fieldTotal = fieldText.split(' ')[2];
  694. if (fieldText == "see all " + fieldTotal + triangleDown){
  695. field.firstElementChild.innerText = "see less " + fieldTotal + triangleUp;
  696. field.style.height = "auto";
  697. } else {
  698. field.firstElementChild.innerText = "see all " + fieldTotal + triangleDown;
  699. field.style.height = "200px";
  700. }
  701. };
  702. </script>
  703. <style>
  704. .see-more{
  705. display: none;
  706. }
  707. .label, .see-more {
  708. position: sticky;
  709. top: 1px;
  710. }
  711. .label{
  712. z-index: 1;
  713. background: white;
  714. padding: 10px 2px 10px 2px;
  715. }
  716. #package-grid, #results-grid {
  717. display: grid;
  718. grid-gap: 2px;
  719. grid-template-columns: min-content 1fr repeat(12, min-content);
  720. }
  721. #results-grid {
  722. grid-template-columns: 3fr 1fr;
  723. }
  724. .data {
  725. border: solid 1px gray;
  726. }
  727. .centered {
  728. text-align: center;
  729. }
  730. .current_version {
  731. overflow: scroll;
  732. width: 21ch;
  733. padding: 10px 2px 10px 2px;
  734. }
  735. .correct, .nopatches, .good_url, .version-good, .cpe-ok, .cve-ok {
  736. background: #d2ffc4;
  737. }
  738. .wrong, .lotsofpatches, .invalid_url, .version-needs-update, .cpe-nok, .cve-nok {
  739. background: #ff9a69;
  740. }
  741. .somepatches, .somewarnings, .missing_url, .version-unknown, .cpe-unknown, .cve-unknown {
  742. background: #ffd870;
  743. }
  744. .cve_ignored, .version-error {
  745. background: #ccc;
  746. }
  747. </style>
  748. <title>Statistics of Buildroot packages</title>
  749. </head>
  750. <body>
  751. <a href="#results">Results</a><br/>
  752. """ # noqa - tabs and spaces
  753. html_footer = """
  754. </body>
  755. </html>
  756. """
  757. def infra_str(infra_list):
  758. if not infra_list:
  759. return "Unknown"
  760. elif len(infra_list) == 1:
  761. return "<b>%s</b><br/>%s" % (infra_list[0][1], infra_list[0][0])
  762. elif infra_list[0][1] == infra_list[1][1]:
  763. return "<b>%s</b><br/>%s + %s" % \
  764. (infra_list[0][1], infra_list[0][0], infra_list[1][0])
  765. else:
  766. return "<b>%s</b> (%s)<br/><b>%s</b> (%s)" % \
  767. (infra_list[0][1], infra_list[0][0],
  768. infra_list[1][1], infra_list[1][0])
  769. def boolean_str(b):
  770. if b:
  771. return "Yes"
  772. else:
  773. return "No"
  774. def dump_html_pkg(f, pkg):
  775. pkg_css_class = pkg.path.replace("/", "_")[:-3]
  776. f.write(f'<div id="tree__{pkg_css_class}" \
  777. class="tree data _{pkg_css_class}">{pkg.tree}</div>\n')
  778. f.write(f'<div id="package__{pkg_css_class}" \
  779. class="package data _{pkg_css_class}">{pkg.path}</div>\n')
  780. # Patch count
  781. data_field_id = f'patch_count__{pkg_css_class}'
  782. div_class = ["centered patch_count data"]
  783. div_class.append(f'_{pkg_css_class}')
  784. if pkg.patch_count == 0:
  785. div_class.append("nopatches")
  786. elif pkg.patch_count < 5:
  787. div_class.append("somepatches")
  788. else:
  789. div_class.append("lotsofpatches")
  790. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)} \
  791. ">{str(pkg.patch_count)}</div>\n')
  792. # Infrastructure
  793. data_field_id = f'infrastructure__{pkg_css_class}'
  794. infra = infra_str(pkg.infras)
  795. div_class = ["centered infrastructure data"]
  796. div_class.append(f'_{pkg_css_class}')
  797. if infra == "Unknown":
  798. div_class.append("wrong")
  799. else:
  800. div_class.append("correct")
  801. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)} \
  802. ">{infra_str(pkg.infras)}</div>\n')
  803. # License
  804. data_field_id = f'license__{pkg_css_class}'
  805. div_class = ["centered license data"]
  806. div_class.append(f'_{pkg_css_class}')
  807. if pkg.is_status_ok('license'):
  808. div_class.append("correct")
  809. else:
  810. div_class.append("wrong")
  811. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)} \
  812. ">{boolean_str(pkg.is_status_ok("license"))}</div>\n')
  813. # License files
  814. data_field_id = f'license_files__{pkg_css_class}'
  815. div_class = ["centered license_files data"]
  816. div_class.append(f'_{pkg_css_class}')
  817. if pkg.is_status_ok('license-files'):
  818. div_class.append("correct")
  819. else:
  820. div_class.append("wrong")
  821. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)} \
  822. ">{boolean_str(pkg.is_status_ok("license-files"))}</div>\n')
  823. # Hash
  824. data_field_id = f'hash_file__{pkg_css_class}'
  825. div_class = ["centered hash_file data"]
  826. div_class.append(f'_{pkg_css_class}')
  827. if pkg.is_status_ok('hash'):
  828. div_class.append("correct")
  829. else:
  830. div_class.append("wrong")
  831. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)} \
  832. ">{boolean_str(pkg.is_status_ok("hash"))}</div>\n')
  833. # Current version
  834. data_field_id = f'current_version__{pkg_css_class}'
  835. current_version = pkg.current_version
  836. f.write(f' <div id="{data_field_id}" \
  837. class="centered current_version data _{pkg_css_class}">{current_version}</div>\n')
  838. # Latest version
  839. data_field_id = f'latest_version__{pkg_css_class}'
  840. div_class = ["centered"]
  841. div_class.append(f'_{pkg_css_class}')
  842. div_class.append("latest_version data")
  843. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  844. div_class.append("version-error")
  845. if pkg.latest_version['version'] is None:
  846. div_class.append("version-unknown")
  847. elif pkg.latest_version['version'] != pkg.current_version:
  848. div_class.append("version-needs-update")
  849. else:
  850. div_class.append("version-good")
  851. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  852. latest_version_text = "<b>Error</b>"
  853. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  854. latest_version_text = "<b>Not found</b>"
  855. else:
  856. if pkg.latest_version['version'] is None:
  857. latest_version_text = "<b>Found, but no version</b>"
  858. else:
  859. latest_version_text = f"""<a href="https://release-monitoring.org/project/{pkg.latest_version['id']}">""" \
  860. f"""<b>{str(pkg.latest_version['version'])}</b></a>"""
  861. latest_version_text += "<br/>"
  862. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  863. latest_version_text += 'found by <a href="https://release-monitoring.org/distro/Buildroot/">distro</a>'
  864. else:
  865. latest_version_text += "found by guess"
  866. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">{latest_version_text}</div>\n')
  867. # Warnings
  868. data_field_id = f'warnings__{pkg_css_class}'
  869. div_class = ["centered warnings data"]
  870. div_class.append(f'_{pkg_css_class}')
  871. if pkg.warnings == 0:
  872. div_class.append("correct")
  873. elif pkg.warnings < 5:
  874. div_class.append("somewarnings")
  875. else:
  876. div_class.append("wrong")
  877. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">{pkg.warnings}</div>\n')
  878. # URL status
  879. data_field_id = f'upstream_url__{pkg_css_class}'
  880. div_class = ["centered upstream_url data"]
  881. div_class.append(f'_{pkg_css_class}')
  882. url_str = pkg.status['url'][1]
  883. if pkg.status['url'][0] in ("error", "warning"):
  884. div_class.append("missing_url")
  885. if pkg.status['url'][0] == "error":
  886. div_class.append("invalid_url")
  887. url_str = f"""<a href="{pkg.url}">{pkg.status['url'][1]}</a>"""
  888. else:
  889. div_class.append("good_url")
  890. url_str = f'<a href="{pkg.url}">Link</a>'
  891. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">{url_str}</div>\n')
  892. # CVEs
  893. data_field_id = f'cves__{pkg_css_class}'
  894. div_class = ["centered cves data"]
  895. div_class.append(f'_{pkg_css_class}')
  896. cve_total = len(pkg.cves) + len(pkg.unsure_cves)
  897. if cve_total > 10:
  898. div_class.append("collapse")
  899. if pkg.is_status_ok("cve"):
  900. div_class.append("cve-ok")
  901. elif pkg.is_status_error("cve"):
  902. div_class.append("cve-nok")
  903. elif pkg.is_status_na("cve") and not pkg.is_actual_package:
  904. div_class.append("cve-ok")
  905. else:
  906. div_class.append("cve-unknown")
  907. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">\n')
  908. if cve_total > 10:
  909. f.write(f' <div onclick="expandField(\'{data_field_id}\')" \
  910. class="see-more centered cve_ignored">see all ({cve_total}) &#9662;</div>\n')
  911. if pkg.is_status_error("cve"):
  912. for cve in cvecheck.CVE.sort_id(pkg.cves):
  913. f.write(f' <a href="https://security-tracker.debian.org/tracker/{cve}">{cve}</a><br/>\n')
  914. for cve in cvecheck.CVE.sort_id(pkg.unsure_cves):
  915. f.write(f' <a href="https://security-tracker.debian.org/tracker/{cve}">{cve} <i>(unsure)</i></a><br/>\n')
  916. elif pkg.is_status_na("cve"):
  917. f.write(f""" {pkg.status['cve'][1]}""")
  918. else:
  919. f.write(" N/A\n")
  920. f.write(" </div>\n")
  921. # CVEs Ignored
  922. data_field_id = f'ignored_cves__{pkg_css_class}'
  923. div_class = ["centered data ignored_cves"]
  924. div_class.append(f'_{pkg_css_class}')
  925. if pkg.ignored_cves:
  926. div_class.append("cve_ignored")
  927. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">\n')
  928. for ignored_cve in pkg.ignored_cves:
  929. f.write(f' <a href="https://security-tracker.debian.org/tracker/{ignored_cve}">{ignored_cve}</a><br/>\n')
  930. f.write(" </div>\n")
  931. # CPE ID
  932. data_field_id = f'cpe_id__{pkg_css_class}'
  933. div_class = ["left cpe_id data"]
  934. div_class.append(f'_{pkg_css_class}')
  935. if pkg.is_status_ok("cpe"):
  936. div_class.append("cpe-ok")
  937. elif pkg.is_status_error("cpe"):
  938. div_class.append("cpe-nok")
  939. elif pkg.is_status_na("cpe") and not pkg.is_actual_package:
  940. div_class.append("cpe-ok")
  941. else:
  942. div_class.append("cpe-unknown")
  943. f.write(f' <div id="{data_field_id}" class="{" ".join(div_class)}">\n')
  944. if pkg.cpeid:
  945. cpeid_begin = ":".join(pkg.cpeid.split(":")[0:4]) + ":"
  946. cpeid_formatted = pkg.cpeid.replace(cpeid_begin, cpeid_begin + "<wbr>")
  947. f.write(" <code>%s</code>\n" % cpeid_formatted)
  948. if not pkg.is_status_ok("cpe"):
  949. if pkg.is_actual_package and pkg.current_version:
  950. if pkg.cpeid:
  951. f.write(f""" <br/>{pkg.status['cpe'][1]} <a href="https://nvd.nist.gov/products/cpe/search/results?"""
  952. f"""namingFormat=2.3&keyword={":".join(pkg.cpeid.split(":")[0:5])}">(Search)</a>\n""")
  953. else:
  954. f.write(f""" {pkg.status['cpe'][1]} <a href="https://nvd.nist.gov/products/cpe/search/results?"""
  955. f"""namingFormat=2.3&keyword={pkg.name}">(Search)</a>\n""")
  956. else:
  957. f.write(" %s\n" % pkg.status['cpe'][1])
  958. f.write(" </div>\n")
  959. def dump_html_all_pkgs(f, packages):
  960. f.write("""
  961. <div id="package-grid">
  962. <div style="grid-column: 1;" onclick="sortGrid(this.id)" id="tree"
  963. class="tree data label"><span>Tree</span><span></span></div>
  964. <div style="grid-column: 2;" onclick="sortGrid(this.id)" id="package"
  965. class="package data label"><span>Package</span><span></span></div>
  966. <div style="grid-column: 3;" onclick="sortGrid(this.id)" id="patch_count"
  967. class="centered patch_count data label"><span>Patch count</span><span></span></div>
  968. <div style="grid-column: 4;" onclick="sortGrid(this.id)" id="infrastructure"
  969. class="centered infrastructure data label">Infrastructure<span></span></div>
  970. <div style="grid-column: 5;" onclick="sortGrid(this.id)" id="license"
  971. class="centered license data label"><span>License</span><span></span></div>
  972. <div style="grid-column: 6;" onclick="sortGrid(this.id)" id="license_files"
  973. class="centered license_files data label"><span>License files</span><span></span></div>
  974. <div style="grid-column: 7;" onclick="sortGrid(this.id)" id="hash_file"
  975. class="centered hash_file data label"><span>Hash file</span><span></span></div>
  976. <div style="grid-column: 8;" onclick="sortGrid(this.id)" id="current_version"
  977. class="centered current_version data label"><span>Current version</span><span></span></div>
  978. <div style="grid-column: 9;" onclick="sortGrid(this.id)" id="latest_version"
  979. class="centered latest_version data label"><span>Latest version</span><span></span></div>
  980. <div style="grid-column: 10;" onclick="sortGrid(this.id)" id="warnings"
  981. class="centered warnings data label"><span>Warnings</span><span></span></div>
  982. <div style="grid-column: 11;" onclick="sortGrid(this.id)" id="upstream_url"
  983. class="centered upstream_url data label"><span>Upstream URL</span><span></span></div>
  984. <div style="grid-column: 12;" onclick="sortGrid(this.id)" id="cves"
  985. class="centered cves data label"><span>CVEs</span><span></span></div>
  986. <div style="grid-column: 13;" onclick="sortGrid(this.id)" id="ignored_cves"
  987. class="centered ignored_cves data label"><span>CVEs Ignored</span><span></span></div>
  988. <div style="grid-column: 14;" onclick="sortGrid(this.id)" id="cpe_id"
  989. class="centered cpe_id data label"><span>CPE ID</span><span></span></div>
  990. """)
  991. for pkg in sorted(packages):
  992. dump_html_pkg(f, pkg)
  993. f.write("</div>")
  994. def dump_html_stats(f, stats):
  995. f.write('<a id="results"></a>\n')
  996. f.write('<div class="data" id="results-grid">\n')
  997. infras = [infra[6:] for infra in stats.keys() if infra.startswith("infra-")]
  998. for infra in infras:
  999. f.write(' <div class="data">Packages using the <i>%s</i> infrastructure</div><div class="data">%s</div>\n' %
  1000. (infra, stats["infra-%s" % infra]))
  1001. f.write(' <div class="data">Packages having license information</div><div class="data">%s</div>\n' %
  1002. stats["license"])
  1003. f.write(' <div class="data">Packages not having license information</div><div class="data">%s</div>\n' %
  1004. stats["no-license"])
  1005. f.write(' <div class="data">Packages having license files information</div><div class="data">%s</div>\n' %
  1006. stats["license-files"])
  1007. f.write(' <div class="data">Packages not having license files information</div><div class="data">%s</div>\n' %
  1008. stats["no-license-files"])
  1009. f.write(' <div class="data">Packages having a hash file</div><div class="data">%s</div>\n' %
  1010. stats["hash"])
  1011. f.write(' <div class="data">Packages not having a hash file</div><div class="data">%s</div>\n' %
  1012. stats["no-hash"])
  1013. f.write(' <div class="data">Total number of patches</div><div class="data">%s</div>\n' %
  1014. stats["patches"])
  1015. f.write('<div class="data">Packages having a mapping on <i>release-monitoring.org</i></div><div class="data">%s</div>\n' %
  1016. stats["rmo-mapping"])
  1017. f.write('<div class="data">Packages lacking a mapping on <i>release-monitoring.org</i></div><div class="data">%s</div>\n' %
  1018. stats["rmo-no-mapping"])
  1019. f.write('<div class="data">Packages that are up-to-date</div><div class="data">%s</div>\n' %
  1020. stats["version-uptodate"])
  1021. f.write('<div class="data">Packages that are not up-to-date</div><div class="data">%s</div>\n' %
  1022. stats["version-not-uptodate"])
  1023. f.write('<div class="data">Packages with no known upstream version</div><div class="data">%s</div>\n' %
  1024. stats["version-unknown"])
  1025. f.write('<div class="data">Packages affected by CVEs</div><div class="data">%s</div>\n' %
  1026. stats["pkg-cves"])
  1027. f.write('<div class="data">Total number of CVEs affecting all packages</div><div class="data">%s</div>\n' %
  1028. stats["total-cves"])
  1029. f.write('<div class="data">Packages affected by unsure CVEs</div><div class="data">%s</div>\n' %
  1030. stats["pkg-unsure-cves"])
  1031. f.write('<div class="data">Total number of unsure CVEs affecting all packages</div><div class="data">%s</div>\n' %
  1032. stats["total-unsure-cves"])
  1033. f.write('<div class="data">Packages with CPE ID</div><div class="data">%s</div>\n' %
  1034. stats["cpe-id"])
  1035. f.write('<div class="data">Packages without CPE ID</div><div class="data">%s</div>\n' %
  1036. stats["no-cpe-id"])
  1037. f.write('</div>\n')
  1038. def dump_html_gen_info(f, date, commit):
  1039. # Updated on Mon Feb 19 08:12:08 CET 2018, Git commit aa77030b8f5e41f1c53eb1c1ad664b8c814ba032
  1040. f.write("<p><i>Updated on %s, git commit %s</i></p>\n" % (str(date), commit))
  1041. def dump_html(packages, stats, date, commit, output):
  1042. with open(output, 'w') as f:
  1043. f.write(html_header)
  1044. dump_html_all_pkgs(f, packages)
  1045. dump_html_stats(f, stats)
  1046. dump_html_gen_info(f, date, commit)
  1047. f.write(html_footer)
  1048. def dump_json(packages, defconfigs, stats, date, commit, output):
  1049. # Format packages as a dictionary instead of a list
  1050. # Exclude local field that does not contains real date
  1051. excluded_fields = ['url_worker', 'name', 'tree_path']
  1052. pkgs = {
  1053. pkg.name: {
  1054. k: v
  1055. for k, v in pkg.__dict__.items()
  1056. if k not in excluded_fields
  1057. } for pkg in packages
  1058. }
  1059. defconfigs = {
  1060. d.name: {
  1061. k: v
  1062. for k, v in d.__dict__.items()
  1063. } for d in defconfigs
  1064. }
  1065. # Aggregate infrastructures into a single dict entry
  1066. statistics = {
  1067. k: v
  1068. for k, v in stats.items()
  1069. if not k.startswith('infra-')
  1070. }
  1071. statistics['infra'] = {k[6:]: v for k, v in stats.items() if k.startswith('infra-')}
  1072. # The actual structure to dump, add commit and date to it
  1073. final = {'packages': pkgs,
  1074. 'stats': statistics,
  1075. 'defconfigs': defconfigs,
  1076. 'package_status_checks': Package.status_checks,
  1077. 'commit': commit,
  1078. 'date': str(date)}
  1079. with open(output, 'w') as f:
  1080. json.dump(final, f, indent=2, separators=(',', ': '))
  1081. f.write('\n')
  1082. def resolvepath(path):
  1083. return os.path.abspath(os.path.expanduser(path))
  1084. def list_str(values):
  1085. return values.split(',')
  1086. def parse_args():
  1087. parser = argparse.ArgumentParser()
  1088. output = parser.add_argument_group('output', 'Output file(s)')
  1089. output.add_argument('--html', dest='html', type=resolvepath,
  1090. help='HTML output file')
  1091. output.add_argument('--json', dest='json', type=resolvepath,
  1092. help='JSON output file')
  1093. packages = parser.add_mutually_exclusive_group()
  1094. packages.add_argument('-c', dest='configpackages', action='store_true',
  1095. help='Apply to packages enabled in current configuration')
  1096. packages.add_argument('-n', dest='npackages', type=int, action='store',
  1097. help='Number of packages')
  1098. packages.add_argument('-p', dest='packages', action='store',
  1099. help='List of packages (comma separated)')
  1100. parser.add_argument('--nvd-path', dest='nvd_path',
  1101. help='Path to the local NVD database', type=resolvepath)
  1102. parser.add_argument('--disable', type=list_str,
  1103. help='Features to disable, comma-separated (cve, upstream, url, warning)',
  1104. default=[])
  1105. args = parser.parse_args()
  1106. if not args.html and not args.json:
  1107. parser.error('at least one of --html or --json (or both) is required')
  1108. return args
  1109. def __main__():
  1110. global cvecheck
  1111. args = parse_args()
  1112. if args.nvd_path:
  1113. import cve as cvecheck
  1114. show_info_js = None
  1115. if args.packages:
  1116. package_list = args.packages.split(",")
  1117. elif args.configpackages:
  1118. show_info_js = get_show_info_js()
  1119. package_list = set([v["name"] for v in show_info_js.values() if 'name' in v])
  1120. else:
  1121. package_list = None
  1122. date = datetime.datetime.now(datetime.timezone.utc)
  1123. commit = subprocess.check_output(['git', '-C', brpath,
  1124. 'rev-parse',
  1125. 'HEAD']).splitlines()[0].decode()
  1126. print("Build package list ...")
  1127. all_trees = get_trees()
  1128. packages = get_pkglist(all_trees, args.npackages, package_list)
  1129. print("Getting developers ...")
  1130. developers = parse_developers()
  1131. print("Build defconfig list ...")
  1132. defconfigs = get_defconfig_list()
  1133. for d in defconfigs:
  1134. d.set_developers(developers)
  1135. print("Getting package make info ...")
  1136. package_init_make_info()
  1137. print("Getting package details ...")
  1138. for pkg in packages:
  1139. pkg.set_infra(show_info_js)
  1140. pkg.set_license()
  1141. pkg.set_hash_info()
  1142. pkg.set_patch_count()
  1143. if "warnings" not in args.disable:
  1144. pkg.set_check_package_warnings()
  1145. pkg.set_current_version()
  1146. pkg.set_cpeid()
  1147. pkg.set_url()
  1148. pkg.set_ignored_cves()
  1149. pkg.set_developers(developers)
  1150. if "url" not in args.disable:
  1151. print("Checking URL status")
  1152. loop = asyncio.get_event_loop()
  1153. loop.run_until_complete(check_package_urls(packages))
  1154. if "upstream" not in args.disable:
  1155. print("Getting latest versions ...")
  1156. loop = asyncio.get_event_loop()
  1157. loop.run_until_complete(check_package_latest_version(packages))
  1158. if "cve" not in args.disable and args.nvd_path:
  1159. print("Checking packages CVEs")
  1160. check_package_cves(args.nvd_path, packages)
  1161. print("Calculate stats")
  1162. stats = calculate_stats(packages)
  1163. if args.html:
  1164. print("Write HTML")
  1165. dump_html(packages, stats, date, commit, args.html)
  1166. if args.json:
  1167. print("Write JSON")
  1168. dump_json(packages, defconfigs, stats, date, commit, args.json)
  1169. __main__()