pkg-stats 33 KB

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