license.bbclass 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. #
  2. # Copyright OpenEmbedded Contributors
  3. #
  4. # SPDX-License-Identifier: MIT
  5. #
  6. # Populates LICENSE_DIRECTORY as set in distro config with the license files as set by
  7. # LIC_FILES_CHKSUM.
  8. # TODO:
  9. # - There is a real issue revolving around license naming standards.
  10. LICENSE_DIRECTORY ??= "${DEPLOY_DIR}/licenses"
  11. LICSSTATEDIR = "${WORKDIR}/license-destdir/"
  12. # Create extra package with license texts and add it to RRECOMMENDS:${PN}
  13. LICENSE_CREATE_PACKAGE[type] = "boolean"
  14. LICENSE_CREATE_PACKAGE ??= "0"
  15. LICENSE_PACKAGE_SUFFIX ??= "-lic"
  16. LICENSE_FILES_DIRECTORY ??= "${datadir}/licenses/"
  17. addtask populate_lic after do_patch before do_build
  18. do_populate_lic[dirs] = "${LICSSTATEDIR}/${PN}"
  19. do_populate_lic[cleandirs] = "${LICSSTATEDIR}"
  20. python do_populate_lic() {
  21. """
  22. Populate LICENSE_DIRECTORY with licenses.
  23. """
  24. lic_files_paths = find_license_files(d)
  25. # The base directory we wrangle licenses to
  26. destdir = os.path.join(d.getVar('LICSSTATEDIR'), d.getVar('PN'))
  27. copy_license_files(lic_files_paths, destdir)
  28. info = get_recipe_info(d)
  29. with open(os.path.join(destdir, "recipeinfo"), "w") as f:
  30. for key in sorted(info.keys()):
  31. f.write("%s: %s\n" % (key, info[key]))
  32. oe.qa.exit_if_errors(d)
  33. }
  34. PSEUDO_IGNORE_PATHS .= ",${@','.join(((d.getVar('COMMON_LICENSE_DIR') or '') + ' ' + (d.getVar('LICENSE_PATH') or '') + ' ' + d.getVar('COREBASE') + '/meta/COPYING').split())}"
  35. # it would be better to copy them in do_install:append, but find_license_filesa is python
  36. python perform_packagecopy:prepend () {
  37. enabled = oe.data.typed_value('LICENSE_CREATE_PACKAGE', d)
  38. if d.getVar('CLASSOVERRIDE') == 'class-target' and enabled:
  39. lic_files_paths = find_license_files(d)
  40. # LICENSE_FILES_DIRECTORY starts with '/' so os.path.join cannot be used to join D and LICENSE_FILES_DIRECTORY
  41. destdir = d.getVar('D') + os.path.join(d.getVar('LICENSE_FILES_DIRECTORY'), d.getVar('PN'))
  42. copy_license_files(lic_files_paths, destdir)
  43. add_package_and_files(d)
  44. }
  45. perform_packagecopy[vardeps] += "LICENSE_CREATE_PACKAGE"
  46. def get_recipe_info(d):
  47. info = {}
  48. info["PV"] = d.getVar("PV")
  49. info["PR"] = d.getVar("PR")
  50. info["LICENSE"] = d.getVar("LICENSE")
  51. return info
  52. def add_package_and_files(d):
  53. packages = d.getVar('PACKAGES')
  54. files = d.getVar('LICENSE_FILES_DIRECTORY')
  55. pn = d.getVar('PN')
  56. pn_lic = "%s%s" % (pn, d.getVar('LICENSE_PACKAGE_SUFFIX', False))
  57. if pn_lic in packages.split():
  58. bb.warn("%s package already existed in %s." % (pn_lic, pn))
  59. else:
  60. # first in PACKAGES to be sure that nothing else gets LICENSE_FILES_DIRECTORY
  61. d.setVar('PACKAGES', "%s %s" % (pn_lic, packages))
  62. d.setVar('FILES:' + pn_lic, files)
  63. def copy_license_files(lic_files_paths, destdir):
  64. import shutil
  65. import errno
  66. bb.utils.mkdirhier(destdir)
  67. for (basename, path, beginline, endline) in lic_files_paths:
  68. try:
  69. src = path
  70. dst = os.path.join(destdir, basename)
  71. if os.path.exists(dst):
  72. os.remove(dst)
  73. if os.path.islink(src):
  74. src = os.path.realpath(src)
  75. canlink = os.access(src, os.W_OK) and (os.stat(src).st_dev == os.stat(destdir).st_dev) and beginline is None and endline is None
  76. if canlink:
  77. try:
  78. os.link(src, dst)
  79. except OSError as err:
  80. if err.errno == errno.EXDEV:
  81. # Copy license files if hardlink is not possible even if st_dev is the
  82. # same on source and destination (docker container with device-mapper?)
  83. canlink = False
  84. else:
  85. raise
  86. # Only chown if we did hardlink and we're running under pseudo
  87. if canlink and os.environ.get('PSEUDO_DISABLED') == '0':
  88. os.chown(dst,0,0)
  89. if not canlink:
  90. begin_idx = max(0, int(beginline) - 1) if beginline is not None else None
  91. end_idx = max(0, int(endline)) if endline is not None else None
  92. if begin_idx is None and end_idx is None:
  93. shutil.copyfile(src, dst)
  94. else:
  95. with open(src, 'rb') as src_f:
  96. with open(dst, 'wb') as dst_f:
  97. dst_f.write(b''.join(src_f.readlines()[begin_idx:end_idx]))
  98. except Exception as e:
  99. bb.warn("Could not copy license file %s to %s: %s" % (src, dst, e))
  100. def find_license_files(d):
  101. """
  102. Creates list of files used in LIC_FILES_CHKSUM and generic LICENSE files.
  103. """
  104. import shutil
  105. import oe.license
  106. from collections import defaultdict, OrderedDict
  107. # All the license files for the package
  108. lic_files = d.getVar('LIC_FILES_CHKSUM') or ""
  109. pn = d.getVar('PN')
  110. # The license files are located in S/LIC_FILE_CHECKSUM.
  111. srcdir = d.getVar('S')
  112. # Directory we store the generic licenses as set in the distro configuration
  113. generic_directory = d.getVar('COMMON_LICENSE_DIR')
  114. # List of basename, path tuples
  115. lic_files_paths = []
  116. # hash for keep track generic lics mappings
  117. non_generic_lics = {}
  118. # Entries from LIC_FILES_CHKSUM
  119. lic_chksums = {}
  120. license_source_dirs = []
  121. license_source_dirs.append(generic_directory)
  122. try:
  123. additional_lic_dirs = d.getVar('LICENSE_PATH').split()
  124. for lic_dir in additional_lic_dirs:
  125. license_source_dirs.append(lic_dir)
  126. except:
  127. pass
  128. class FindVisitor(oe.license.LicenseVisitor):
  129. def visit_Str(self, node):
  130. #
  131. # Until I figure out what to do with
  132. # the two modifiers I support (or greater = +
  133. # and "with exceptions" being *
  134. # we'll just strip out the modifier and put
  135. # the base license.
  136. find_license(node.s.replace("+", "").replace("*", ""))
  137. self.generic_visit(node)
  138. def visit_Constant(self, node):
  139. find_license(node.value.replace("+", "").replace("*", ""))
  140. self.generic_visit(node)
  141. def find_license(license_type):
  142. try:
  143. bb.utils.mkdirhier(gen_lic_dest)
  144. except:
  145. pass
  146. spdx_generic = None
  147. license_source = None
  148. # If the generic does not exist we need to check to see if there is an SPDX mapping to it,
  149. # unless NO_GENERIC_LICENSE is set.
  150. for lic_dir in license_source_dirs:
  151. if not os.path.isfile(os.path.join(lic_dir, license_type)):
  152. if d.getVarFlag('SPDXLICENSEMAP', license_type) != None:
  153. # Great, there is an SPDXLICENSEMAP. We can copy!
  154. bb.debug(1, "We need to use a SPDXLICENSEMAP for %s" % (license_type))
  155. spdx_generic = d.getVarFlag('SPDXLICENSEMAP', license_type)
  156. license_source = lic_dir
  157. break
  158. elif os.path.isfile(os.path.join(lic_dir, license_type)):
  159. spdx_generic = license_type
  160. license_source = lic_dir
  161. break
  162. non_generic_lic = d.getVarFlag('NO_GENERIC_LICENSE', license_type)
  163. if spdx_generic and license_source:
  164. # we really should copy to generic_ + spdx_generic, however, that ends up messing the manifest
  165. # audit up. This should be fixed in emit_pkgdata (or, we actually got and fix all the recipes)
  166. lic_files_paths.append(("generic_" + license_type, os.path.join(license_source, spdx_generic),
  167. None, None))
  168. # The user may attempt to use NO_GENERIC_LICENSE for a generic license which doesn't make sense
  169. # and should not be allowed, warn the user in this case.
  170. if d.getVarFlag('NO_GENERIC_LICENSE', license_type):
  171. oe.qa.handle_error("license-no-generic",
  172. "%s: %s is a generic license, please don't use NO_GENERIC_LICENSE for it." % (pn, license_type), d)
  173. elif non_generic_lic and non_generic_lic in lic_chksums:
  174. # if NO_GENERIC_LICENSE is set, we copy the license files from the fetched source
  175. # of the package rather than the license_source_dirs.
  176. lic_files_paths.append(("generic_" + license_type,
  177. os.path.join(srcdir, non_generic_lic), None, None))
  178. non_generic_lics[non_generic_lic] = license_type
  179. else:
  180. # Explicitly avoid the CLOSED license because this isn't generic
  181. if license_type != 'CLOSED':
  182. # And here is where we warn people that their licenses are lousy
  183. oe.qa.handle_error("license-exists",
  184. "%s: No generic license file exists for: %s in any provider" % (pn, license_type), d)
  185. pass
  186. if not generic_directory:
  187. bb.fatal("COMMON_LICENSE_DIR is unset. Please set this in your distro config")
  188. for url in lic_files.split():
  189. try:
  190. (method, host, path, user, pswd, parm) = bb.fetch.decodeurl(url)
  191. if method != "file" or not path:
  192. raise bb.fetch.MalformedUrl()
  193. except bb.fetch.MalformedUrl:
  194. bb.fatal("%s: LIC_FILES_CHKSUM contains an invalid URL: %s" % (d.getVar('PF'), url))
  195. # We want the license filename and path
  196. chksum = parm.get('md5', None)
  197. beginline = parm.get('beginline')
  198. endline = parm.get('endline')
  199. lic_chksums[path] = (chksum, beginline, endline)
  200. v = FindVisitor()
  201. try:
  202. v.visit_string(d.getVar('LICENSE'))
  203. except oe.license.InvalidLicense as exc:
  204. bb.fatal('%s: %s' % (d.getVar('PF'), exc))
  205. except SyntaxError:
  206. oe.qa.handle_error("license-syntax",
  207. "%s: Failed to parse it's LICENSE field." % (d.getVar('PF')), d)
  208. # Add files from LIC_FILES_CHKSUM to list of license files
  209. lic_chksum_paths = defaultdict(OrderedDict)
  210. for path, data in sorted(lic_chksums.items()):
  211. lic_chksum_paths[os.path.basename(path)][data] = (os.path.join(srcdir, path), data[1], data[2])
  212. for basename, files in lic_chksum_paths.items():
  213. if len(files) == 1:
  214. # Don't copy again a LICENSE already handled as non-generic
  215. if basename in non_generic_lics:
  216. continue
  217. data = list(files.values())[0]
  218. lic_files_paths.append(tuple([basename] + list(data)))
  219. else:
  220. # If there are multiple different license files with identical
  221. # basenames we rename them to <file>.0, <file>.1, ...
  222. for i, data in enumerate(files.values()):
  223. lic_files_paths.append(tuple(["%s.%d" % (basename, i)] + list(data)))
  224. return lic_files_paths
  225. def return_spdx(d, license):
  226. """
  227. This function returns the spdx mapping of a license if it exists.
  228. """
  229. return d.getVarFlag('SPDXLICENSEMAP', license)
  230. def canonical_license(d, license):
  231. """
  232. Return the canonical (SPDX) form of the license if available (so GPLv3
  233. becomes GPL-3.0-only) or the passed license if there is no canonical form.
  234. """
  235. return d.getVarFlag('SPDXLICENSEMAP', license) or license
  236. def expand_wildcard_licenses(d, wildcard_licenses):
  237. """
  238. There are some common wildcard values users may want to use. Support them
  239. here.
  240. """
  241. licenses = set(wildcard_licenses)
  242. mapping = {
  243. "AGPL-3.0*" : ["AGPL-3.0-only", "AGPL-3.0-or-later"],
  244. "GPL-3.0*" : ["GPL-3.0-only", "GPL-3.0-or-later"],
  245. "LGPL-3.0*" : ["LGPL-3.0-only", "LGPL-3.0-or-later"],
  246. }
  247. for k in mapping:
  248. if k in wildcard_licenses:
  249. licenses.remove(k)
  250. for item in mapping[k]:
  251. licenses.add(item)
  252. for l in licenses:
  253. if l in oe.license.obsolete_license_list():
  254. bb.fatal("Error, %s is an obsolete license, please use an SPDX reference in INCOMPATIBLE_LICENSE" % l)
  255. if "*" in l:
  256. bb.fatal("Error, %s is an invalid license wildcard entry" % l)
  257. return list(licenses)
  258. def incompatible_license_contains(license, truevalue, falsevalue, d):
  259. license = canonical_license(d, license)
  260. bad_licenses = (d.getVar('INCOMPATIBLE_LICENSE') or "").split()
  261. bad_licenses = expand_wildcard_licenses(d, bad_licenses)
  262. return truevalue if license in bad_licenses else falsevalue
  263. def incompatible_pkg_license(d, dont_want_licenses, license):
  264. # Handles an "or" or two license sets provided by
  265. # flattened_licenses(), pick one that works if possible.
  266. def choose_lic_set(a, b):
  267. return a if all(oe.license.license_ok(canonical_license(d, lic),
  268. dont_want_licenses) for lic in a) else b
  269. try:
  270. licenses = oe.license.flattened_licenses(license, choose_lic_set)
  271. except oe.license.LicenseError as exc:
  272. bb.fatal('%s: %s' % (d.getVar('P'), exc))
  273. incompatible_lic = []
  274. for l in licenses:
  275. license = canonical_license(d, l)
  276. if not oe.license.license_ok(license, dont_want_licenses):
  277. incompatible_lic.append(license)
  278. return sorted(incompatible_lic)
  279. def incompatible_license(d, dont_want_licenses, package=None):
  280. """
  281. This function checks if a recipe has only incompatible licenses. It also
  282. take into consideration 'or' operand. dont_want_licenses should be passed
  283. as canonical (SPDX) names.
  284. """
  285. import oe.license
  286. license = d.getVar("LICENSE:%s" % package) if package else None
  287. if not license:
  288. license = d.getVar('LICENSE')
  289. return incompatible_pkg_license(d, dont_want_licenses, license)
  290. def check_license_flags(d):
  291. """
  292. This function checks if a recipe has any LICENSE_FLAGS that
  293. aren't acceptable.
  294. If it does, it returns the all LICENSE_FLAGS missing from the list
  295. of acceptable license flags, or all of the LICENSE_FLAGS if there
  296. is no list of acceptable flags.
  297. If everything is is acceptable, it returns None.
  298. """
  299. def license_flag_matches(flag, acceptlist, pn):
  300. """
  301. Return True if flag matches something in acceptlist, None if not.
  302. Before we test a flag against the acceptlist, we append _${PN}
  303. to it. We then try to match that string against the
  304. acceptlist. This covers the normal case, where we expect
  305. LICENSE_FLAGS to be a simple string like 'commercial', which
  306. the user typically matches exactly in the acceptlist by
  307. explicitly appending the package name e.g 'commercial_foo'.
  308. If we fail the match however, we then split the flag across
  309. '_' and append each fragment and test until we either match or
  310. run out of fragments.
  311. """
  312. flag_pn = ("%s_%s" % (flag, pn))
  313. for candidate in acceptlist:
  314. if flag_pn == candidate:
  315. return True
  316. flag_cur = ""
  317. flagments = flag_pn.split("_")
  318. flagments.pop() # we've already tested the full string
  319. for flagment in flagments:
  320. if flag_cur:
  321. flag_cur += "_"
  322. flag_cur += flagment
  323. for candidate in acceptlist:
  324. if flag_cur == candidate:
  325. return True
  326. return False
  327. def all_license_flags_match(license_flags, acceptlist):
  328. """ Return all unmatched flags, None if all flags match """
  329. pn = d.getVar('PN')
  330. split_acceptlist = acceptlist.split()
  331. flags = []
  332. for flag in license_flags.split():
  333. if not license_flag_matches(flag, split_acceptlist, pn):
  334. flags.append(flag)
  335. return flags if flags else None
  336. license_flags = d.getVar('LICENSE_FLAGS')
  337. if license_flags:
  338. acceptlist = d.getVar('LICENSE_FLAGS_ACCEPTED')
  339. if not acceptlist:
  340. return license_flags.split()
  341. unmatched_flags = all_license_flags_match(license_flags, acceptlist)
  342. if unmatched_flags:
  343. return unmatched_flags
  344. return None
  345. def check_license_format(d):
  346. """
  347. This function checks if LICENSE is well defined,
  348. Validate operators in LICENSES.
  349. No spaces are allowed between LICENSES.
  350. """
  351. pn = d.getVar('PN')
  352. licenses = d.getVar('LICENSE')
  353. from oe.license import license_operator, license_operator_chars, license_pattern
  354. elements = list(filter(lambda x: x.strip(), license_operator.split(licenses)))
  355. for pos, element in enumerate(elements):
  356. if license_pattern.match(element):
  357. if pos > 0 and license_pattern.match(elements[pos - 1]):
  358. oe.qa.handle_error('license-format',
  359. '%s: LICENSE value "%s" has an invalid format - license names ' \
  360. 'must be separated by the following characters to indicate ' \
  361. 'the license selection: %s' %
  362. (pn, licenses, license_operator_chars), d)
  363. elif not license_operator.match(element):
  364. oe.qa.handle_error('license-format',
  365. '%s: LICENSE value "%s" has an invalid separator "%s" that is not ' \
  366. 'in the valid list of separators (%s)' %
  367. (pn, licenses, element, license_operator_chars), d)
  368. SSTATETASKS += "do_populate_lic"
  369. do_populate_lic[sstate-inputdirs] = "${LICSSTATEDIR}"
  370. do_populate_lic[sstate-outputdirs] = "${LICENSE_DIRECTORY}/"
  371. IMAGE_CLASSES:append = " license_image"
  372. python do_populate_lic_setscene () {
  373. sstate_setscene(d)
  374. }
  375. addtask do_populate_lic_setscene