license.bbclass 18 KB

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