swupdate-common.bbclass 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. # Copyright (C) 2015-2022 Stefano Babic
  2. #
  3. # SPDX-License-Identifier: GPLv3
  4. inherit swupdate-lib
  5. DEPENDS += "\
  6. cpio-native \
  7. ${@ 'openssl-native' if d.getVar('SWUPDATE_SIGNING') or d.getVar('SWUPDATE_ENCRYPT_SWDESC') or d.getVarFlags('SWUPDATE_IMAGES_ENCRYPTED') else ''} \
  8. "
  9. do_swuimage[umask] = "022"
  10. SSTATETASKS += "do_swuimage"
  11. SSTATE_SKIP_CREATION_task-swuimage = '1'
  12. SWUDEPLOYDIR = "${WORKDIR}/deploy-${PN}-swuimage"
  13. do_swuimage[dirs] = "${SWUDEPLOYDIR}"
  14. do_swuimage[cleandirs] += "${SWUDEPLOYDIR}"
  15. do_swuimage[sstate-inputdirs] = "${SWUDEPLOYDIR}"
  16. do_swuimage[sstate-outputdirs] = "${DEPLOY_DIR_IMAGE}"
  17. do_swuimage[stamp-extra-info] = "${MACHINE}"
  18. python () {
  19. deps = " " + swupdate_getdepends(d)
  20. d.appendVarFlag('do_swuimage', 'depends', deps)
  21. d.delVarFlag('do_fetch', 'noexec')
  22. d.delVarFlag('do_unpack', 'noexec')
  23. }
  24. def get_pwd_file_args(d, passfile):
  25. pwd_args = []
  26. pwd_file = d.getVar(passfile, True)
  27. if pwd_file:
  28. pwd_args = ["-passin", "file:%s" % pwd_file]
  29. return pwd_args
  30. def swupdate_getdepends(d):
  31. def adddep(depstr, deps):
  32. for i in (depstr or "").split():
  33. if i not in deps:
  34. deps.append(i)
  35. deps = []
  36. images = (d.getVar('IMAGE_DEPENDS', True) or "").split()
  37. for image in images:
  38. adddep(image , deps)
  39. depstr = ""
  40. for dep in deps:
  41. depstr += " " + dep + ":do_build"
  42. return depstr
  43. def swupdate_extract_keys(keyfile_path):
  44. try:
  45. with open(keyfile_path, 'r') as f:
  46. lines = f.readlines()
  47. except IOError:
  48. bb.fatal("Failed to open file with keys %s" % (keyfile))
  49. data = {}
  50. for _ in lines:
  51. k,v = _.split('=',maxsplit=1)
  52. data[k.rstrip()] = v
  53. key = data['key'].rstrip('\n')
  54. iv = data['iv'].rstrip('\n')
  55. return key,iv
  56. def swupdate_write_sha256(s):
  57. import re
  58. write_lines = []
  59. with open(os.path.join(s, "sw-description"), 'r') as f:
  60. for line in f:
  61. shastr = r"sha256.+=.+@(.+\")"
  62. #m = re.match(r"^(?P<before_placeholder>.+)sha256.+=.+(?P<filename>\w+)", line)
  63. m = re.match(r"^(?P<before_placeholder>.+)(sha256|version).+[=:].*(?P<quote>[\'\"])@(?P<filename>.*)(?P=quote)", line)
  64. if m:
  65. filename = m.group('filename')
  66. hash = swupdate_get_sha256(None, s, filename)
  67. write_lines.append(line.replace("@%s" % (filename), hash))
  68. else:
  69. write_lines.append(line)
  70. with open(os.path.join(s, "sw-description"), 'w+') as f:
  71. for line in write_lines:
  72. f.write(line)
  73. def swupdate_exec_functions(d, s, write_lines):
  74. import re
  75. for index, line in enumerate(write_lines):
  76. m = re.match(r"^(?P<before_placeholder>.+)\$(?P<bitbake_function_name>\w+)\((?P<parms>.+)\)(?P<after_placeholder>.+)$", line)
  77. if m:
  78. fun = m.group('bitbake_function_name') + "(d, \"" + s + "\", \"" + m.group('parms') + "\")"
  79. ret = eval(fun)
  80. bb.debug (2, "%s return %s " % (m.group('bitbake_function_name'), ret))
  81. line = m.group('before_placeholder') + ret + m.group('after_placeholder') + "\n"
  82. write_lines[index] = line
  83. def swupdate_expand_bitbake_variables(d, s):
  84. write_lines = []
  85. with open(os.path.join(s, "sw-description"), 'r') as f:
  86. import re
  87. for line in f:
  88. found = False
  89. while True:
  90. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>\w+)@@(?P<after_placeholder>.+)$", line)
  91. if m:
  92. bitbake_variable_value = d.getVar(m.group('bitbake_variable_name'), True)
  93. if bitbake_variable_value is None:
  94. bitbake_variable_value = ""
  95. bb.warn("BitBake variable %s not set" % (m.group('bitbake_variable_name')))
  96. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  97. found = True
  98. continue
  99. else:
  100. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>.+)\[(?P<flag_var_name>.+)\]@@(?P<after_placeholder>.+)$", line)
  101. if m:
  102. bitbake_variable_value = (d.getVarFlag(m.group('bitbake_variable_name'), m.group('flag_var_name'), True) or "")
  103. if bitbake_variable_value is None:
  104. bitbake_variable_value = ""
  105. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  106. continue
  107. if found:
  108. line = line + "\n"
  109. break
  110. write_lines.append(line)
  111. swupdate_exec_functions(d, s, write_lines)
  112. with open(os.path.join(s, "sw-description"), 'w+') as f:
  113. for line in write_lines:
  114. f.write(line)
  115. # Get all the variables referred by the sw-description at parse time.
  116. def swupdate_find_bitbake_variables(d):
  117. import re
  118. vardeps = []
  119. filespath = d.getVar('FILESPATH')
  120. sw_desc_path = bb.utils.which(filespath, "sw-description")
  121. try:
  122. with open(sw_desc_path, "r") as f:
  123. for line in f:
  124. found = False
  125. while True:
  126. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>\w+)@@(?P<after_placeholder>.+)$", line)
  127. if m:
  128. bitbake_variable_value = m.group('bitbake_variable_name')
  129. vardeps.append(bitbake_variable_value)
  130. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  131. found = True
  132. continue
  133. else:
  134. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>.+)\[(?P<flag_var_name>.+)\]@@(?P<after_placeholder>.+)$", line)
  135. if m:
  136. bitbake_variable_value = m.group('bitbake_variable_name')
  137. vardeps.append(bitbake_variable_value)
  138. flag_name = m.group('flag_var_name')
  139. vardeps.append(flag_name)
  140. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  141. continue
  142. break
  143. except IOError:
  144. pass
  145. return ' '.join(set(vardeps))
  146. def swupdate_expand_auto_versions(d, s):
  147. import re
  148. import oe.packagedata
  149. AUTO_VERSION_TAG = "@SWU_AUTO_VERSION"
  150. AUTOVERSION_REGEXP = "version\s*=\s*\"%s" % AUTO_VERSION_TAG
  151. with open(os.path.join(s, "sw-description"), 'r') as f:
  152. data = f.read()
  153. def get_package_name(group, file_list):
  154. package = None
  155. m = re.search(r"%s:(?P<package>.+?(?=[\"@]))" % (AUTOVERSION_REGEXP), group)
  156. if m:
  157. package = m.group('package')
  158. return (package, True)
  159. for filename in file_list:
  160. if filename in group:
  161. package = filename
  162. if not package:
  163. bb.fatal("Failed to find file in group %s" % (group))
  164. return (package, False)
  165. def get_packagedata_key(group):
  166. m = re.search(r"%s.+?(?<=@)(?P<key>.+?(?=\"))" % (AUTOVERSION_REGEXP), group)
  167. if m:
  168. return (m.group('key'), True)
  169. return ("PV", False)
  170. regexp = re.compile(r"\{[^\{]*%s.[^\}]*\}" % (AUTOVERSION_REGEXP))
  171. while True:
  172. m = regexp.search(data)
  173. if not m:
  174. break
  175. group = data[m.start():m.end()]
  176. (package, pkg_name_defined) = get_package_name(group, (d.getVar('SWUPDATE_IMAGES', True) or "").split())
  177. pkg_info = os.path.join(d.getVar('PKGDATA_DIR'), 'runtime-reverse', package)
  178. pkgdata = oe.packagedata.read_pkgdatafile(pkg_info)
  179. (key, key_defined) = get_packagedata_key(group)
  180. if not key in pkgdata.keys():
  181. bb.warn("\"%s\" not set for package %s - using \"1.0\"" % (key, package))
  182. version = "1.0"
  183. else:
  184. version = pkgdata[key].split('+')[0]
  185. replace_str = AUTO_VERSION_TAG
  186. if pkg_name_defined:
  187. replace_str = replace_str + ":" + package
  188. if key_defined:
  189. replace_str = replace_str + "@" + key
  190. group = group.replace(replace_str, version)
  191. data = data[:m.start()] + group + data[m.end():]
  192. with open(os.path.join(s, "sw-description"), 'w+') as f:
  193. f.write(data)
  194. def prepare_sw_description(d):
  195. import shutil
  196. import subprocess
  197. s = d.getVar('S', True)
  198. swupdate_expand_bitbake_variables(d, s)
  199. swupdate_expand_auto_versions(d, s)
  200. swupdate_write_sha256(s)
  201. encrypt = d.getVar('SWUPDATE_ENCRYPT_SWDESC', True)
  202. if encrypt:
  203. bb.note("Encryption of sw-description")
  204. shutil.copyfile(os.path.join(s, 'sw-description'), os.path.join(s, 'sw-description.plain'))
  205. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  206. swupdate_encrypt_file(os.path.join(s, 'sw-description.plain'), os.path.join(s, 'sw-description'), key, iv)
  207. signing = d.getVar('SWUPDATE_SIGNING', True)
  208. if signing == "1":
  209. bb.warn('SWUPDATE_SIGNING = "1" is deprecated, falling back to "RSA". It is advised to set it to "RSA" if using RSA signing.')
  210. signing = "RSA"
  211. if signing:
  212. sw_desc_sig = os.path.join(s, 'sw-description.sig')
  213. sw_desc = os.path.join(s, 'sw-description.plain' if encrypt else 'sw-description')
  214. if signing == "CUSTOM":
  215. signcmd = []
  216. sign_tool = d.getVar('SWUPDATE_SIGN_TOOL', True)
  217. signtool = sign_tool.split()
  218. for i in range(len(signtool)):
  219. signcmd.append(signtool[i])
  220. if not signcmd:
  221. bb.fatal("Custom SWUPDATE_SIGN_TOOL is not given")
  222. elif signing == "RSA":
  223. privkey = d.getVar('SWUPDATE_PRIVATE_KEY', True)
  224. if not privkey:
  225. bb.fatal("SWUPDATE_PRIVATE_KEY isn't set")
  226. if not os.path.exists(privkey):
  227. bb.fatal("SWUPDATE_PRIVATE_KEY %s doesn't exist" % (privkey))
  228. signcmd = ["openssl", "dgst", "-sha256", "-sign", privkey] + get_pwd_file_args(d, 'SWUPDATE_PASSWORD_FILE') + ["-out", sw_desc_sig, sw_desc]
  229. elif signing == "CMS":
  230. cms_cert = d.getVar('SWUPDATE_CMS_CERT', True)
  231. if not cms_cert:
  232. bb.fatal("SWUPDATE_CMS_CERT is not set")
  233. if not os.path.exists(cms_cert):
  234. bb.fatal("SWUPDATE_CMS_CERT %s doesn't exist" % (cms_cert))
  235. cms_key = d.getVar('SWUPDATE_CMS_KEY', True)
  236. if not cms_key:
  237. bb.fatal("SWUPDATE_CMS_KEY isn't set")
  238. if not os.path.exists(cms_key):
  239. bb.fatal("SWUPDATE_CMS_KEY %s doesn't exist" % (cms_key))
  240. signcmd = ["openssl", "cms", "-sign", "-in", sw_desc, "-out", sw_desc_sig, "-signer", cms_cert, "-inkey", cms_key] + \
  241. get_pwd_file_args(d, 'SWUPDATE_PASSWORD_FILE') + ["-outform", "DER", "-nosmimecap", "-binary"]
  242. else:
  243. bb.fatal("Unrecognized SWUPDATE_SIGNING mechanism.")
  244. subprocess.run(' '.join(signcmd), shell=True, check=True)
  245. def swupdate_add_src_uri(d, list_for_cpio):
  246. import shutil
  247. s = d.getVar('S', True)
  248. fetch = bb.fetch2.Fetch([], d)
  249. # Add files listed in SRC_URI to the swu file
  250. for url in fetch.urls:
  251. local = fetch.localpath(url)
  252. filename = os.path.basename(local)
  253. aes_file = d.getVar('SWUPDATE_AES_FILE', True)
  254. if aes_file:
  255. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  256. if (filename != 'sw-description') and (os.path.isfile(local)):
  257. encrypted = (d.getVarFlag("SWUPDATE_IMAGES_ENCRYPTED", filename, True) or "")
  258. dst = os.path.join(s, "%s" % filename )
  259. if encrypted == '1':
  260. bb.note("Encryption requested for %s" %(filename))
  261. if not key or not iv:
  262. bb.fatal("Encryption required, but no key found")
  263. swupdate_encrypt_file(local, dst, key, iv)
  264. else:
  265. shutil.copyfile(local, dst)
  266. list_for_cpio.append(filename)
  267. def add_image_to_swu(d, deploydir, imagename, s, encrypt, list_for_cpio):
  268. import shutil
  269. src = os.path.join(deploydir, imagename)
  270. if not os.path.isfile(src):
  271. return False
  272. target_imagename = os.path.basename(imagename) # allow images in subfolders of DEPLOY_DIR_IMAGE
  273. dst = os.path.join(s, target_imagename)
  274. if encrypt == '1':
  275. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  276. bb.note("Encryption requested for %s" %(imagename))
  277. swupdate_encrypt_file(src, dst, key, iv)
  278. else:
  279. shutil.copyfile(src, dst)
  280. list_for_cpio.append(target_imagename)
  281. return True
  282. def swupdate_add_artifacts(d, list_for_cpio):
  283. import shutil
  284. # Search for images listed in SWUPDATE_IMAGES in the DEPLOY directory.
  285. images = (d.getVar('SWUPDATE_IMAGES', True) or "").split()
  286. deploydir = d.getVar('DEPLOY_DIR_IMAGE', True)
  287. imgdeploydir = d.getVar('SWUDEPLOYDIR', True)
  288. s = d.getVar('S', True)
  289. for image in images:
  290. fstypes = (d.getVarFlag("SWUPDATE_IMAGES_FSTYPES", image, True) or "").split()
  291. encrypted = (d.getVarFlag("SWUPDATE_IMAGES_ENCRYPTED", image, True) or "")
  292. if fstypes:
  293. noappend_machine = d.getVarFlag("SWUPDATE_IMAGES_NOAPPEND_MACHINE", image, True)
  294. if noappend_machine == "0": # Search for a file explicitly with MACHINE
  295. imagebases = [ image + '-' + d.getVar('MACHINE', True) ]
  296. elif noappend_machine == "1": # Search for a file explicitly without MACHINE
  297. imagebases = [ image ]
  298. else: # None, means auto mode. Just try to find an image file with MACHINE or without MACHINE
  299. imagebases = [ image + '-' + d.getVar('MACHINE', True), image ]
  300. for fstype in fstypes:
  301. image_found = False
  302. for imagebase in imagebases:
  303. image_found = add_image_to_swu(d, deploydir, imagebase + fstype, s, encrypted, list_for_cpio)
  304. if image_found:
  305. break
  306. if not image_found:
  307. bb.fatal("swupdate cannot find image file: %s" % os.path.join(deploydir, imagebase + fstype))
  308. else: # Allow also complete entries like "image.ext4.gz" in SWUPDATE_IMAGES
  309. if not add_image_to_swu(d, deploydir, image, s, encrypted, list_for_cpio):
  310. bb.fatal("swupdate cannot find %s image file" % image)
  311. def swupdate_create_cpio(d, swudeploydir, list_for_cpio):
  312. s = d.getVar('S', True)
  313. os.chdir(s)
  314. updateimage = d.getVar('IMAGE_NAME', True) + '.swu'
  315. updateimage_link = d.getVar('IMAGE_LINK_NAME', True) + '.swu'
  316. line = 'for i in ' + ' '.join(list_for_cpio) + '; do echo $i;done | cpio -ov -H crc > ' + os.path.join(swudeploydir, updateimage)
  317. os.system(line)
  318. os.chdir(swudeploydir)
  319. os.symlink(updateimage, updateimage_link)
  320. python do_swuimage () {
  321. import shutil
  322. list_for_cpio = ["sw-description"]
  323. workdir = d.getVar('WORKDIR', True)
  324. s = d.getVar('S', True)
  325. imgdeploydir = d.getVar('SWUDEPLOYDIR', True)
  326. shutil.copyfile(os.path.join(workdir, "sw-description"), os.path.join(s, "sw-description"))
  327. if d.getVar('SWUPDATE_SIGNING', True):
  328. list_for_cpio.append('sw-description.sig')
  329. # Add artifacts added via SRC_URI
  330. if not d.getVar('INHIBIT_SWUPDATE_ADD_SRC_URI', True):
  331. swupdate_add_src_uri(d, list_for_cpio)
  332. # Add artifacts set via SWUPDATE_IMAGES
  333. swupdate_add_artifacts(d, list_for_cpio)
  334. prepare_sw_description(d)
  335. swupdate_create_cpio(d, imgdeploydir, list_for_cpio)
  336. }