pkg-stats 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. #!/usr/bin/env python3
  2. # Copyright (C) 2009 by Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. # General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. import aiohttp
  18. import argparse
  19. import asyncio
  20. import datetime
  21. import fnmatch
  22. import os
  23. from collections import defaultdict
  24. import re
  25. import subprocess
  26. import requests # NVD database download
  27. import json
  28. import time
  29. import sys
  30. sys.path.append('utils/')
  31. from getdeveloperlib import parse_developers # noqa: E402
  32. import cve as cvecheck
  33. INFRA_RE = re.compile(r"\$\(eval \$\(([a-z-]*)-package\)\)")
  34. URL_RE = re.compile(r"\s*https?://\S*\s*$")
  35. RM_API_STATUS_ERROR = 1
  36. RM_API_STATUS_FOUND_BY_DISTRO = 2
  37. RM_API_STATUS_FOUND_BY_PATTERN = 3
  38. RM_API_STATUS_NOT_FOUND = 4
  39. class Defconfig:
  40. def __init__(self, name, path):
  41. self.name = name
  42. self.path = path
  43. self.developers = None
  44. def set_developers(self, developers):
  45. """
  46. Fills in the .developers field
  47. """
  48. self.developers = [
  49. developer.name
  50. for developer in developers
  51. if developer.hasfile(self.path)
  52. ]
  53. def get_defconfig_list():
  54. """
  55. Builds the list of Buildroot defconfigs, returning a list of Defconfig
  56. objects.
  57. """
  58. return [
  59. Defconfig(name[:-len('_defconfig')], os.path.join('configs', name))
  60. for name in os.listdir('configs')
  61. if name.endswith('_defconfig')
  62. ]
  63. class Package:
  64. all_licenses = dict()
  65. all_license_files = list()
  66. all_versions = dict()
  67. all_ignored_cves = dict()
  68. # This is the list of all possible checks. Add new checks to this list so
  69. # a tool that post-processeds the json output knows the checks before
  70. # iterating over the packages.
  71. status_checks = ['cve', 'developers', 'hash', 'license',
  72. 'license-files', 'patches', 'pkg-check', 'url', 'version']
  73. def __init__(self, name, path):
  74. self.name = name
  75. self.path = path
  76. self.pkg_path = os.path.dirname(path)
  77. self.infras = None
  78. self.license = None
  79. self.has_license = False
  80. self.has_license_files = False
  81. self.has_hash = False
  82. self.patch_files = []
  83. self.warnings = 0
  84. self.current_version = None
  85. self.url = None
  86. self.url_worker = None
  87. self.cves = list()
  88. self.latest_version = {'status': RM_API_STATUS_ERROR, 'version': None, 'id': None}
  89. self.status = {}
  90. def pkgvar(self):
  91. return self.name.upper().replace("-", "_")
  92. def set_url(self):
  93. """
  94. Fills in the .url field
  95. """
  96. self.status['url'] = ("warning", "no Config.in")
  97. for filename in os.listdir(os.path.dirname(self.path)):
  98. if fnmatch.fnmatch(filename, 'Config.*'):
  99. fp = open(os.path.join(os.path.dirname(self.path), filename), "r")
  100. for config_line in fp:
  101. if URL_RE.match(config_line):
  102. self.url = config_line.strip()
  103. self.status['url'] = ("ok", "found")
  104. fp.close()
  105. return
  106. self.status['url'] = ("error", "missing")
  107. fp.close()
  108. @property
  109. def patch_count(self):
  110. return len(self.patch_files)
  111. @property
  112. def has_valid_infra(self):
  113. try:
  114. if self.infras[0][1] == 'virtual':
  115. return False
  116. except IndexError:
  117. return False
  118. return True
  119. def set_infra(self):
  120. """
  121. Fills in the .infras field
  122. """
  123. self.infras = list()
  124. with open(self.path, 'r') as f:
  125. lines = f.readlines()
  126. for l in lines:
  127. match = INFRA_RE.match(l)
  128. if not match:
  129. continue
  130. infra = match.group(1)
  131. if infra.startswith("host-"):
  132. self.infras.append(("host", infra[5:]))
  133. else:
  134. self.infras.append(("target", infra))
  135. def set_license(self):
  136. """
  137. Fills in the .status['license'] and .status['license-files'] fields
  138. """
  139. if not self.has_valid_infra:
  140. self.status['license'] = ("na", "no valid package infra")
  141. self.status['license-files'] = ("na", "no valid package infra")
  142. return
  143. var = self.pkgvar()
  144. self.status['license'] = ("error", "missing")
  145. self.status['license-files'] = ("error", "missing")
  146. if var in self.all_licenses:
  147. self.license = self.all_licenses[var]
  148. self.status['license'] = ("ok", "found")
  149. if var in self.all_license_files:
  150. self.status['license-files'] = ("ok", "found")
  151. def set_hash_info(self):
  152. """
  153. Fills in the .status['hash'] field
  154. """
  155. if not self.has_valid_infra:
  156. self.status['hash'] = ("na", "no valid package infra")
  157. self.status['hash-license'] = ("na", "no valid package infra")
  158. return
  159. hashpath = self.path.replace(".mk", ".hash")
  160. if os.path.exists(hashpath):
  161. self.status['hash'] = ("ok", "found")
  162. else:
  163. self.status['hash'] = ("error", "missing")
  164. def set_patch_count(self):
  165. """
  166. Fills in the .patch_count, .patch_files and .status['patches'] fields
  167. """
  168. if not self.has_valid_infra:
  169. self.status['patches'] = ("na", "no valid package infra")
  170. return
  171. pkgdir = os.path.dirname(self.path)
  172. for subdir, _, _ in os.walk(pkgdir):
  173. self.patch_files = fnmatch.filter(os.listdir(subdir), '*.patch')
  174. if self.patch_count == 0:
  175. self.status['patches'] = ("ok", "no patches")
  176. elif self.patch_count < 5:
  177. self.status['patches'] = ("warning", "some patches")
  178. else:
  179. self.status['patches'] = ("error", "lots of patches")
  180. def set_current_version(self):
  181. """
  182. Fills in the .current_version field
  183. """
  184. var = self.pkgvar()
  185. if var in self.all_versions:
  186. self.current_version = self.all_versions[var]
  187. def set_check_package_warnings(self):
  188. """
  189. Fills in the .warnings and .status['pkg-check'] fields
  190. """
  191. cmd = ["./utils/check-package"]
  192. pkgdir = os.path.dirname(self.path)
  193. self.status['pkg-check'] = ("error", "Missing")
  194. for root, dirs, files in os.walk(pkgdir):
  195. for f in files:
  196. if f.endswith(".mk") or f.endswith(".hash") or f == "Config.in" or f == "Config.in.host":
  197. cmd.append(os.path.join(root, f))
  198. o = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[1]
  199. lines = o.splitlines()
  200. for line in lines:
  201. m = re.match("^([0-9]*) warnings generated", line.decode())
  202. if m:
  203. self.warnings = int(m.group(1))
  204. if self.warnings == 0:
  205. self.status['pkg-check'] = ("ok", "no warnings")
  206. else:
  207. self.status['pkg-check'] = ("error", "{} warnings".format(self.warnings))
  208. return
  209. @property
  210. def ignored_cves(self):
  211. """
  212. Give the list of CVEs ignored by the package
  213. """
  214. return list(self.all_ignored_cves.get(self.pkgvar(), []))
  215. def set_developers(self, developers):
  216. """
  217. Fills in the .developers and .status['developers'] field
  218. """
  219. self.developers = [
  220. dev.name
  221. for dev in developers
  222. if dev.hasfile(self.path)
  223. ]
  224. if self.developers:
  225. self.status['developers'] = ("ok", "{} developers".format(len(self.developers)))
  226. else:
  227. self.status['developers'] = ("warning", "no developers")
  228. def is_status_ok(self, name):
  229. return self.status[name][0] == 'ok'
  230. def __eq__(self, other):
  231. return self.path == other.path
  232. def __lt__(self, other):
  233. return self.path < other.path
  234. def __str__(self):
  235. return "%s (path='%s', license='%s', license_files='%s', hash='%s', patches=%d)" % \
  236. (self.name, self.path, self.is_status_ok('license'),
  237. self.is_status_ok('license-files'), self.status['hash'], self.patch_count)
  238. def get_pkglist(npackages, package_list):
  239. """
  240. Builds the list of Buildroot packages, returning a list of Package
  241. objects. Only the .name and .path fields of the Package object are
  242. initialized.
  243. npackages: limit to N packages
  244. package_list: limit to those packages in this list
  245. """
  246. WALK_USEFUL_SUBDIRS = ["boot", "linux", "package", "toolchain"]
  247. WALK_EXCLUDES = ["boot/common.mk",
  248. "linux/linux-ext-.*.mk",
  249. "package/freescale-imx/freescale-imx.mk",
  250. "package/gcc/gcc.mk",
  251. "package/gstreamer/gstreamer.mk",
  252. "package/gstreamer1/gstreamer1.mk",
  253. "package/gtk2-themes/gtk2-themes.mk",
  254. "package/matchbox/matchbox.mk",
  255. "package/opengl/opengl.mk",
  256. "package/qt5/qt5.mk",
  257. "package/x11r7/x11r7.mk",
  258. "package/doc-asciidoc.mk",
  259. "package/pkg-.*.mk",
  260. "package/nvidia-tegra23/nvidia-tegra23.mk",
  261. "toolchain/toolchain-external/pkg-toolchain-external.mk",
  262. "toolchain/toolchain-external/toolchain-external.mk",
  263. "toolchain/toolchain.mk",
  264. "toolchain/helpers.mk",
  265. "toolchain/toolchain-wrapper.mk"]
  266. packages = list()
  267. count = 0
  268. for root, dirs, files in os.walk("."):
  269. rootdir = root.split("/")
  270. if len(rootdir) < 2:
  271. continue
  272. if rootdir[1] not in WALK_USEFUL_SUBDIRS:
  273. continue
  274. for f in files:
  275. if not f.endswith(".mk"):
  276. continue
  277. # Strip ending ".mk"
  278. pkgname = f[:-3]
  279. if package_list and pkgname not in package_list:
  280. continue
  281. pkgpath = os.path.join(root, f)
  282. skip = False
  283. for exclude in WALK_EXCLUDES:
  284. # pkgpath[2:] strips the initial './'
  285. if re.match(exclude, pkgpath[2:]):
  286. skip = True
  287. continue
  288. if skip:
  289. continue
  290. p = Package(pkgname, pkgpath)
  291. packages.append(p)
  292. count += 1
  293. if npackages and count == npackages:
  294. return packages
  295. return packages
  296. def package_init_make_info():
  297. # Fetch all variables at once
  298. variables = subprocess.check_output(["make", "BR2_HAVE_DOT_CONFIG=y", "-s", "printvars",
  299. "VARS=%_LICENSE %_LICENSE_FILES %_VERSION %_IGNORE_CVES"])
  300. variable_list = variables.decode().splitlines()
  301. # We process first the host package VERSION, and then the target
  302. # package VERSION. This means that if a package exists in both
  303. # target and host variants, with different values (eg. version
  304. # numbers (unlikely)), we'll report the target one.
  305. variable_list = [x[5:] for x in variable_list if x.startswith("HOST_")] + \
  306. [x for x in variable_list if not x.startswith("HOST_")]
  307. for l in variable_list:
  308. # Get variable name and value
  309. pkgvar, value = l.split("=")
  310. # Strip the suffix according to the variable
  311. if pkgvar.endswith("_LICENSE"):
  312. # If value is "unknown", no license details available
  313. if value == "unknown":
  314. continue
  315. pkgvar = pkgvar[:-8]
  316. Package.all_licenses[pkgvar] = value
  317. elif pkgvar.endswith("_LICENSE_FILES"):
  318. if pkgvar.endswith("_MANIFEST_LICENSE_FILES"):
  319. continue
  320. pkgvar = pkgvar[:-14]
  321. Package.all_license_files.append(pkgvar)
  322. elif pkgvar.endswith("_VERSION"):
  323. if pkgvar.endswith("_DL_VERSION"):
  324. continue
  325. pkgvar = pkgvar[:-8]
  326. Package.all_versions[pkgvar] = value
  327. elif pkgvar.endswith("_IGNORE_CVES"):
  328. pkgvar = pkgvar[:-12]
  329. Package.all_ignored_cves[pkgvar] = value.split()
  330. check_url_count = 0
  331. async def check_url_status(session, pkg, npkgs, retry=True):
  332. global check_url_count
  333. try:
  334. async with session.get(pkg.url) as resp:
  335. if resp.status >= 400:
  336. pkg.status['url'] = ("error", "invalid {}".format(resp.status))
  337. check_url_count += 1
  338. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  339. return
  340. except (aiohttp.ClientError, asyncio.TimeoutError):
  341. if retry:
  342. return await check_url_status(session, pkg, npkgs, retry=False)
  343. else:
  344. pkg.status['url'] = ("error", "invalid (err)")
  345. check_url_count += 1
  346. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  347. return
  348. pkg.status['url'] = ("ok", "valid")
  349. check_url_count += 1
  350. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  351. async def check_package_urls(packages):
  352. tasks = []
  353. connector = aiohttp.TCPConnector(limit_per_host=5)
  354. async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
  355. packages = [p for p in packages if p.status['url'][0] == 'ok']
  356. for pkg in packages:
  357. tasks.append(check_url_status(sess, pkg, len(packages)))
  358. await asyncio.wait(tasks)
  359. def check_package_latest_version_set_status(pkg, status, version, identifier):
  360. pkg.latest_version = {
  361. "status": status,
  362. "version": version,
  363. "id": identifier,
  364. }
  365. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  366. pkg.status['version'] = ('warning', "Release Monitoring API error")
  367. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  368. pkg.status['version'] = ('warning', "Package not found on Release Monitoring")
  369. if pkg.latest_version['version'] is None:
  370. pkg.status['version'] = ('warning', "No upstream version available on Release Monitoring")
  371. elif pkg.latest_version['version'] != pkg.current_version:
  372. pkg.status['version'] = ('error', "The newer version {} is available upstream".format(pkg.latest_version['version']))
  373. else:
  374. pkg.status['version'] = ('ok', 'up-to-date')
  375. async def check_package_get_latest_version_by_distro(session, pkg, retry=True):
  376. url = "https://release-monitoring.org//api/project/Buildroot/%s" % pkg.name
  377. try:
  378. async with session.get(url) as resp:
  379. if resp.status != 200:
  380. return False
  381. data = await resp.json()
  382. version = data['version'] if 'version' in data else None
  383. check_package_latest_version_set_status(pkg,
  384. RM_API_STATUS_FOUND_BY_DISTRO,
  385. version,
  386. data['id'])
  387. return True
  388. except (aiohttp.ClientError, asyncio.TimeoutError):
  389. if retry:
  390. return await check_package_get_latest_version_by_distro(session, pkg, retry=False)
  391. else:
  392. return False
  393. async def check_package_get_latest_version_by_guess(session, pkg, retry=True):
  394. url = "https://release-monitoring.org/api/projects/?pattern=%s" % pkg.name
  395. try:
  396. async with session.get(url) as resp:
  397. if resp.status != 200:
  398. return False
  399. data = await resp.json()
  400. # filter projects that have the right name and a version defined
  401. projects = [p for p in data['projects'] if p['name'] == pkg.name and 'version' in p]
  402. projects.sort(key=lambda x: x['id'])
  403. if len(projects) > 0:
  404. check_package_latest_version_set_status(pkg,
  405. RM_API_STATUS_FOUND_BY_DISTRO,
  406. projects[0]['version'],
  407. projects[0]['id'])
  408. return True
  409. except (aiohttp.ClientError, asyncio.TimeoutError):
  410. if retry:
  411. return await check_package_get_latest_version_by_guess(session, pkg, retry=False)
  412. else:
  413. return False
  414. check_latest_count = 0
  415. async def check_package_latest_version_get(session, pkg, npkgs):
  416. global check_latest_count
  417. if await check_package_get_latest_version_by_distro(session, pkg):
  418. check_latest_count += 1
  419. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  420. return
  421. if await check_package_get_latest_version_by_guess(session, pkg):
  422. check_latest_count += 1
  423. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  424. return
  425. check_package_latest_version_set_status(pkg,
  426. RM_API_STATUS_NOT_FOUND,
  427. None, None)
  428. check_latest_count += 1
  429. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  430. async def check_package_latest_version(packages):
  431. """
  432. Fills in the .latest_version field of all Package objects
  433. This field is a dict and has the following keys:
  434. - status: one of RM_API_STATUS_ERROR,
  435. RM_API_STATUS_FOUND_BY_DISTRO, RM_API_STATUS_FOUND_BY_PATTERN,
  436. RM_API_STATUS_NOT_FOUND
  437. - version: string containing the latest version known by
  438. release-monitoring.org for this package
  439. - id: string containing the id of the project corresponding to this
  440. package, as known by release-monitoring.org
  441. """
  442. for pkg in [p for p in packages if not p.has_valid_infra]:
  443. pkg.status['version'] = ("na", "no valid package infra")
  444. tasks = []
  445. connector = aiohttp.TCPConnector(limit_per_host=5)
  446. async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
  447. packages = [p for p in packages if p.has_valid_infra]
  448. for pkg in packages:
  449. tasks.append(check_package_latest_version_get(sess, pkg, len(packages)))
  450. await asyncio.wait(tasks)
  451. def check_package_cves(nvd_path, packages):
  452. if not os.path.isdir(nvd_path):
  453. os.makedirs(nvd_path)
  454. for cve in cvecheck.CVE.read_nvd_dir(nvd_path):
  455. for pkg_name in cve.pkg_names:
  456. if pkg_name in packages:
  457. pkg = packages[pkg_name]
  458. if cve.affects(pkg.name, pkg.current_version, pkg.ignored_cves) == cve.CVE_AFFECTS :
  459. pkg.cves.append(cve.identifier)
  460. def calculate_stats(packages):
  461. stats = defaultdict(int)
  462. stats['packages'] = len(packages)
  463. for pkg in packages:
  464. # If packages have multiple infra, take the first one. For the
  465. # vast majority of packages, the target and host infra are the
  466. # same. There are very few packages that use a different infra
  467. # for the host and target variants.
  468. if len(pkg.infras) > 0:
  469. infra = pkg.infras[0][1]
  470. stats["infra-%s" % infra] += 1
  471. else:
  472. stats["infra-unknown"] += 1
  473. if pkg.is_status_ok('license'):
  474. stats["license"] += 1
  475. else:
  476. stats["no-license"] += 1
  477. if pkg.is_status_ok('license-files'):
  478. stats["license-files"] += 1
  479. else:
  480. stats["no-license-files"] += 1
  481. if pkg.is_status_ok('hash'):
  482. stats["hash"] += 1
  483. else:
  484. stats["no-hash"] += 1
  485. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  486. stats["rmo-mapping"] += 1
  487. else:
  488. stats["rmo-no-mapping"] += 1
  489. if not pkg.latest_version['version']:
  490. stats["version-unknown"] += 1
  491. elif pkg.latest_version['version'] == pkg.current_version:
  492. stats["version-uptodate"] += 1
  493. else:
  494. stats["version-not-uptodate"] += 1
  495. stats["patches"] += pkg.patch_count
  496. stats["total-cves"] += len(pkg.cves)
  497. if len(pkg.cves) != 0:
  498. stats["pkg-cves"] += 1
  499. return stats
  500. html_header = """
  501. <head>
  502. <script src=\"https://www.kryogenix.org/code/browser/sorttable/sorttable.js\"></script>
  503. <style type=\"text/css\">
  504. table {
  505. width: 100%;
  506. }
  507. td {
  508. border: 1px solid black;
  509. }
  510. td.centered {
  511. text-align: center;
  512. }
  513. td.wrong {
  514. background: #ff9a69;
  515. }
  516. td.correct {
  517. background: #d2ffc4;
  518. }
  519. td.nopatches {
  520. background: #d2ffc4;
  521. }
  522. td.somepatches {
  523. background: #ffd870;
  524. }
  525. td.lotsofpatches {
  526. background: #ff9a69;
  527. }
  528. td.good_url {
  529. background: #d2ffc4;
  530. }
  531. td.missing_url {
  532. background: #ffd870;
  533. }
  534. td.invalid_url {
  535. background: #ff9a69;
  536. }
  537. td.version-good {
  538. background: #d2ffc4;
  539. }
  540. td.version-needs-update {
  541. background: #ff9a69;
  542. }
  543. td.version-unknown {
  544. background: #ffd870;
  545. }
  546. td.version-error {
  547. background: #ccc;
  548. }
  549. </style>
  550. <title>Statistics of Buildroot packages</title>
  551. </head>
  552. <a href=\"#results\">Results</a><br/>
  553. <p id=\"sortable_hint\"></p>
  554. """
  555. html_footer = """
  556. </body>
  557. <script>
  558. if (typeof sorttable === \"object\") {
  559. document.getElementById(\"sortable_hint\").innerHTML =
  560. \"hint: the table can be sorted by clicking the column headers\"
  561. }
  562. </script>
  563. </html>
  564. """
  565. def infra_str(infra_list):
  566. if not infra_list:
  567. return "Unknown"
  568. elif len(infra_list) == 1:
  569. return "<b>%s</b><br/>%s" % (infra_list[0][1], infra_list[0][0])
  570. elif infra_list[0][1] == infra_list[1][1]:
  571. return "<b>%s</b><br/>%s + %s" % \
  572. (infra_list[0][1], infra_list[0][0], infra_list[1][0])
  573. else:
  574. return "<b>%s</b> (%s)<br/><b>%s</b> (%s)" % \
  575. (infra_list[0][1], infra_list[0][0],
  576. infra_list[1][1], infra_list[1][0])
  577. def boolean_str(b):
  578. if b:
  579. return "Yes"
  580. else:
  581. return "No"
  582. def dump_html_pkg(f, pkg):
  583. f.write(" <tr>\n")
  584. f.write(" <td>%s</td>\n" % pkg.path[2:])
  585. # Patch count
  586. td_class = ["centered"]
  587. if pkg.patch_count == 0:
  588. td_class.append("nopatches")
  589. elif pkg.patch_count < 5:
  590. td_class.append("somepatches")
  591. else:
  592. td_class.append("lotsofpatches")
  593. f.write(" <td class=\"%s\">%s</td>\n" %
  594. (" ".join(td_class), str(pkg.patch_count)))
  595. # Infrastructure
  596. infra = infra_str(pkg.infras)
  597. td_class = ["centered"]
  598. if infra == "Unknown":
  599. td_class.append("wrong")
  600. else:
  601. td_class.append("correct")
  602. f.write(" <td class=\"%s\">%s</td>\n" %
  603. (" ".join(td_class), infra_str(pkg.infras)))
  604. # License
  605. td_class = ["centered"]
  606. if pkg.is_status_ok('license'):
  607. td_class.append("correct")
  608. else:
  609. td_class.append("wrong")
  610. f.write(" <td class=\"%s\">%s</td>\n" %
  611. (" ".join(td_class), boolean_str(pkg.is_status_ok('license'))))
  612. # License files
  613. td_class = ["centered"]
  614. if pkg.is_status_ok('license-files'):
  615. td_class.append("correct")
  616. else:
  617. td_class.append("wrong")
  618. f.write(" <td class=\"%s\">%s</td>\n" %
  619. (" ".join(td_class), boolean_str(pkg.is_status_ok('license-files'))))
  620. # Hash
  621. td_class = ["centered"]
  622. if pkg.is_status_ok('hash'):
  623. td_class.append("correct")
  624. else:
  625. td_class.append("wrong")
  626. f.write(" <td class=\"%s\">%s</td>\n" %
  627. (" ".join(td_class), boolean_str(pkg.is_status_ok('hash'))))
  628. # Current version
  629. if len(pkg.current_version) > 20:
  630. current_version = pkg.current_version[:20] + "..."
  631. else:
  632. current_version = pkg.current_version
  633. f.write(" <td class=\"centered\">%s</td>\n" % current_version)
  634. # Latest version
  635. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  636. td_class.append("version-error")
  637. if pkg.latest_version['version'] is None:
  638. td_class.append("version-unknown")
  639. elif pkg.latest_version['version'] != pkg.current_version:
  640. td_class.append("version-needs-update")
  641. else:
  642. td_class.append("version-good")
  643. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  644. latest_version_text = "<b>Error</b>"
  645. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  646. latest_version_text = "<b>Not found</b>"
  647. else:
  648. if pkg.latest_version['version'] is None:
  649. latest_version_text = "<b>Found, but no version</b>"
  650. else:
  651. latest_version_text = "<a href=\"https://release-monitoring.org/project/%s\"><b>%s</b></a>" % \
  652. (pkg.latest_version['id'], str(pkg.latest_version['version']))
  653. latest_version_text += "<br/>"
  654. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  655. latest_version_text += "found by <a href=\"https://release-monitoring.org/distro/Buildroot/\">distro</a>"
  656. else:
  657. latest_version_text += "found by guess"
  658. f.write(" <td class=\"%s\">%s</td>\n" %
  659. (" ".join(td_class), latest_version_text))
  660. # Warnings
  661. td_class = ["centered"]
  662. if pkg.warnings == 0:
  663. td_class.append("correct")
  664. else:
  665. td_class.append("wrong")
  666. f.write(" <td class=\"%s\">%d</td>\n" %
  667. (" ".join(td_class), pkg.warnings))
  668. # URL status
  669. td_class = ["centered"]
  670. url_str = pkg.status['url'][1]
  671. if pkg.status['url'][0] in ("error", "warning"):
  672. td_class.append("missing_url")
  673. if pkg.status['url'][0] == "error":
  674. td_class.append("invalid_url")
  675. url_str = "<a href=%s>%s</a>" % (pkg.url, pkg.status['url'][1])
  676. else:
  677. td_class.append("good_url")
  678. url_str = "<a href=%s>Link</a>" % pkg.url
  679. f.write(" <td class=\"%s\">%s</td>\n" %
  680. (" ".join(td_class), url_str))
  681. # CVEs
  682. td_class = ["centered"]
  683. if len(pkg.cves) == 0:
  684. td_class.append("correct")
  685. else:
  686. td_class.append("wrong")
  687. f.write(" <td class=\"%s\">\n" % " ".join(td_class))
  688. for cve in pkg.cves:
  689. f.write(" <a href=\"https://security-tracker.debian.org/tracker/%s\">%s<br/>\n" % (cve, cve))
  690. f.write(" </td>\n")
  691. f.write(" </tr>\n")
  692. def dump_html_all_pkgs(f, packages):
  693. f.write("""
  694. <table class=\"sortable\">
  695. <tr>
  696. <td>Package</td>
  697. <td class=\"centered\">Patch count</td>
  698. <td class=\"centered\">Infrastructure</td>
  699. <td class=\"centered\">License</td>
  700. <td class=\"centered\">License files</td>
  701. <td class=\"centered\">Hash file</td>
  702. <td class=\"centered\">Current version</td>
  703. <td class=\"centered\">Latest version</td>
  704. <td class=\"centered\">Warnings</td>
  705. <td class=\"centered\">Upstream URL</td>
  706. <td class=\"centered\">CVEs</td>
  707. </tr>
  708. """)
  709. for pkg in sorted(packages):
  710. dump_html_pkg(f, pkg)
  711. f.write("</table>")
  712. def dump_html_stats(f, stats):
  713. f.write("<a id=\"results\"></a>\n")
  714. f.write("<table>\n")
  715. infras = [infra[6:] for infra in stats.keys() if infra.startswith("infra-")]
  716. for infra in infras:
  717. f.write(" <tr><td>Packages using the <i>%s</i> infrastructure</td><td>%s</td></tr>\n" %
  718. (infra, stats["infra-%s" % infra]))
  719. f.write(" <tr><td>Packages having license information</td><td>%s</td></tr>\n" %
  720. stats["license"])
  721. f.write(" <tr><td>Packages not having license information</td><td>%s</td></tr>\n" %
  722. stats["no-license"])
  723. f.write(" <tr><td>Packages having license files information</td><td>%s</td></tr>\n" %
  724. stats["license-files"])
  725. f.write(" <tr><td>Packages not having license files information</td><td>%s</td></tr>\n" %
  726. stats["no-license-files"])
  727. f.write(" <tr><td>Packages having a hash file</td><td>%s</td></tr>\n" %
  728. stats["hash"])
  729. f.write(" <tr><td>Packages not having a hash file</td><td>%s</td></tr>\n" %
  730. stats["no-hash"])
  731. f.write(" <tr><td>Total number of patches</td><td>%s</td></tr>\n" %
  732. stats["patches"])
  733. f.write("<tr><td>Packages having a mapping on <i>release-monitoring.org</i></td><td>%s</td></tr>\n" %
  734. stats["rmo-mapping"])
  735. f.write("<tr><td>Packages lacking a mapping on <i>release-monitoring.org</i></td><td>%s</td></tr>\n" %
  736. stats["rmo-no-mapping"])
  737. f.write("<tr><td>Packages that are up-to-date</td><td>%s</td></tr>\n" %
  738. stats["version-uptodate"])
  739. f.write("<tr><td>Packages that are not up-to-date</td><td>%s</td></tr>\n" %
  740. stats["version-not-uptodate"])
  741. f.write("<tr><td>Packages with no known upstream version</td><td>%s</td></tr>\n" %
  742. stats["version-unknown"])
  743. f.write("<tr><td>Packages affected by CVEs</td><td>%s</td></tr>\n" %
  744. stats["pkg-cves"])
  745. f.write("<tr><td>Total number of CVEs affecting all packages</td><td>%s</td></tr>\n" %
  746. stats["total-cves"])
  747. f.write("</table>\n")
  748. def dump_html_gen_info(f, date, commit):
  749. # Updated on Mon Feb 19 08:12:08 CET 2018, Git commit aa77030b8f5e41f1c53eb1c1ad664b8c814ba032
  750. f.write("<p><i>Updated on %s, git commit %s</i></p>\n" % (str(date), commit))
  751. def dump_html(packages, stats, date, commit, output):
  752. with open(output, 'w') as f:
  753. f.write(html_header)
  754. dump_html_all_pkgs(f, packages)
  755. dump_html_stats(f, stats)
  756. dump_html_gen_info(f, date, commit)
  757. f.write(html_footer)
  758. def dump_json(packages, defconfigs, stats, date, commit, output):
  759. # Format packages as a dictionnary instead of a list
  760. # Exclude local field that does not contains real date
  761. excluded_fields = ['url_worker', 'name']
  762. pkgs = {
  763. pkg.name: {
  764. k: v
  765. for k, v in pkg.__dict__.items()
  766. if k not in excluded_fields
  767. } for pkg in packages
  768. }
  769. defconfigs = {
  770. d.name: {
  771. k: v
  772. for k, v in d.__dict__.items()
  773. } for d in defconfigs
  774. }
  775. # Aggregate infrastructures into a single dict entry
  776. statistics = {
  777. k: v
  778. for k, v in stats.items()
  779. if not k.startswith('infra-')
  780. }
  781. statistics['infra'] = {k[6:]: v for k, v in stats.items() if k.startswith('infra-')}
  782. # The actual structure to dump, add commit and date to it
  783. final = {'packages': pkgs,
  784. 'stats': statistics,
  785. 'defconfigs': defconfigs,
  786. 'package_status_checks': Package.status_checks,
  787. 'commit': commit,
  788. 'date': str(date)}
  789. with open(output, 'w') as f:
  790. json.dump(final, f, indent=2, separators=(',', ': '))
  791. f.write('\n')
  792. def resolvepath(path):
  793. return os.path.abspath(os.path.expanduser(path))
  794. def parse_args():
  795. parser = argparse.ArgumentParser()
  796. output = parser.add_argument_group('output', 'Output file(s)')
  797. output.add_argument('--html', dest='html', type=resolvepath,
  798. help='HTML output file')
  799. output.add_argument('--json', dest='json', type=resolvepath,
  800. help='JSON output file')
  801. packages = parser.add_mutually_exclusive_group()
  802. packages.add_argument('-n', dest='npackages', type=int, action='store',
  803. help='Number of packages')
  804. packages.add_argument('-p', dest='packages', action='store',
  805. help='List of packages (comma separated)')
  806. parser.add_argument('--nvd-path', dest='nvd_path',
  807. help='Path to the local NVD database', type=resolvepath)
  808. args = parser.parse_args()
  809. if not args.html and not args.json:
  810. parser.error('at least one of --html or --json (or both) is required')
  811. return args
  812. def __main__():
  813. args = parse_args()
  814. if args.packages:
  815. package_list = args.packages.split(",")
  816. else:
  817. package_list = None
  818. date = datetime.datetime.utcnow()
  819. commit = subprocess.check_output(['git', 'rev-parse',
  820. 'HEAD']).splitlines()[0].decode()
  821. print("Build package list ...")
  822. packages = get_pkglist(args.npackages, package_list)
  823. print("Getting developers ...")
  824. developers = parse_developers()
  825. print("Build defconfig list ...")
  826. defconfigs = get_defconfig_list()
  827. for d in defconfigs:
  828. d.set_developers(developers)
  829. print("Getting package make info ...")
  830. package_init_make_info()
  831. print("Getting package details ...")
  832. for pkg in packages:
  833. pkg.set_infra()
  834. pkg.set_license()
  835. pkg.set_hash_info()
  836. pkg.set_patch_count()
  837. pkg.set_check_package_warnings()
  838. pkg.set_current_version()
  839. pkg.set_url()
  840. pkg.set_developers(developers)
  841. print("Checking URL status")
  842. loop = asyncio.get_event_loop()
  843. loop.run_until_complete(check_package_urls(packages))
  844. print("Getting latest versions ...")
  845. loop = asyncio.get_event_loop()
  846. loop.run_until_complete(check_package_latest_version(packages))
  847. if args.nvd_path:
  848. print("Checking packages CVEs")
  849. check_package_cves(args.nvd_path, {p.name: p for p in packages})
  850. print("Calculate stats")
  851. stats = calculate_stats(packages)
  852. if args.html:
  853. print("Write HTML")
  854. dump_html(packages, stats, date, commit, args.html)
  855. if args.json:
  856. print("Write JSON")
  857. dump_json(packages, defconfigs, stats, date, commit, args.json)
  858. __main__()