swupdate-common.bbclass 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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_write_sha256(s):
  44. import re
  45. write_lines = []
  46. with open(os.path.join(s, "sw-description"), 'r') as f:
  47. for line in f:
  48. shastr = r"sha256.+=.+@(.+\")"
  49. m = re.match(r"^(?P<before_placeholder>.+)(sha256|version).+[=:].*(?P<quote>[\'\"])@(?P<filename>.*)(?P=quote)", line)
  50. if m:
  51. filename = m.group('filename')
  52. bb.warn("Syntax for sha256 changed, please use $swupdate_get_sha256(%s)" % filename)
  53. hash = swupdate_get_sha256(None, s, filename)
  54. write_lines.append(line.replace("@%s" % (filename), hash))
  55. else:
  56. write_lines.append(line)
  57. with open(os.path.join(s, "sw-description"), 'w+') as f:
  58. for line in write_lines:
  59. f.write(line)
  60. def swupdate_exec_functions(d, s, write_lines):
  61. import re
  62. for index, line in enumerate(write_lines):
  63. m = re.match(r"^(?P<before_placeholder>.+)\$(?P<bitbake_function_name>\w+)\((?P<parms>.+)\)(?P<after_placeholder>.+)$", line)
  64. if m:
  65. fun = m.group('bitbake_function_name') + "(d, \"" + s + "\", \"" + m.group('parms') + "\")"
  66. ret = eval(fun)
  67. bb.debug (2, "%s return %s " % (m.group('bitbake_function_name'), ret))
  68. line = m.group('before_placeholder') + ret + m.group('after_placeholder') + "\n"
  69. write_lines[index] = line
  70. def swupdate_expand_bitbake_variables(d, s):
  71. write_lines = []
  72. with open(os.path.join(s, "sw-description"), 'r') as f:
  73. import re
  74. for line in f:
  75. found = False
  76. while True:
  77. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>\w+)@@(?P<after_placeholder>.+)$", line)
  78. if m:
  79. bitbake_variable_value = d.getVar(m.group('bitbake_variable_name'), True)
  80. if bitbake_variable_value is None:
  81. bitbake_variable_value = ""
  82. bb.warn("BitBake variable %s not set" % (m.group('bitbake_variable_name')))
  83. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  84. found = True
  85. continue
  86. else:
  87. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>.+)\[(?P<flag_var_name>.+)\]@@(?P<after_placeholder>.+)$", line)
  88. if m:
  89. bitbake_variable_value = (d.getVarFlag(m.group('bitbake_variable_name'), m.group('flag_var_name'), True) or "")
  90. if bitbake_variable_value is None:
  91. bitbake_variable_value = ""
  92. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  93. continue
  94. if found:
  95. line = line + "\n"
  96. break
  97. write_lines.append(line)
  98. swupdate_exec_functions(d, s, write_lines)
  99. with open(os.path.join(s, "sw-description"), 'w+') as f:
  100. for line in write_lines:
  101. f.write(line)
  102. # Get all the variables referred by the sw-description at parse time.
  103. def swupdate_find_bitbake_variables(d):
  104. import re
  105. vardeps = []
  106. filespath = d.getVar('FILESPATH')
  107. sw_desc_path = bb.utils.which(filespath, "sw-description")
  108. try:
  109. with open(sw_desc_path, "r") as f:
  110. for line in f:
  111. found = False
  112. while True:
  113. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>\w+)@@(?P<after_placeholder>.+)$", line)
  114. if m:
  115. bitbake_variable_value = m.group('bitbake_variable_name')
  116. vardeps.append(bitbake_variable_value)
  117. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  118. found = True
  119. continue
  120. else:
  121. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>.+)\[(?P<flag_var_name>.+)\]@@(?P<after_placeholder>.+)$", line)
  122. if m:
  123. bitbake_variable_value = m.group('bitbake_variable_name')
  124. vardeps.append(bitbake_variable_value)
  125. flag_name = m.group('flag_var_name')
  126. vardeps.append(flag_name)
  127. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  128. continue
  129. break
  130. except IOError:
  131. pass
  132. return ' '.join(set(vardeps))
  133. def prepare_sw_description(d):
  134. import shutil
  135. import subprocess
  136. s = d.getVar('S', True)
  137. swupdate_expand_bitbake_variables(d, s)
  138. swupdate_write_sha256(s)
  139. encrypt = d.getVar('SWUPDATE_ENCRYPT_SWDESC', True)
  140. if encrypt:
  141. bb.note("Encryption of sw-description")
  142. shutil.copyfile(os.path.join(s, 'sw-description'), os.path.join(s, 'sw-description.plain'))
  143. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  144. swupdate_encrypt_file(os.path.join(s, 'sw-description.plain'), os.path.join(s, 'sw-description'), key, iv)
  145. signing = d.getVar('SWUPDATE_SIGNING', True)
  146. if signing == "1":
  147. bb.warn('SWUPDATE_SIGNING = "1" is deprecated, falling back to "RSA". It is advised to set it to "RSA" if using RSA signing.')
  148. signing = "RSA"
  149. if signing:
  150. sw_desc_sig = os.path.join(s, 'sw-description.sig')
  151. sw_desc = os.path.join(s, 'sw-description.plain' if encrypt else 'sw-description')
  152. if signing == "CUSTOM":
  153. signcmd = []
  154. sign_tool = d.getVar('SWUPDATE_SIGN_TOOL', True)
  155. signtool = sign_tool.split()
  156. for i in range(len(signtool)):
  157. signcmd.append(signtool[i])
  158. if not signcmd:
  159. bb.fatal("Custom SWUPDATE_SIGN_TOOL is not given")
  160. elif signing == "RSA":
  161. privkey = d.getVar('SWUPDATE_PRIVATE_KEY', True)
  162. if not privkey:
  163. bb.fatal("SWUPDATE_PRIVATE_KEY isn't set")
  164. if not os.path.exists(privkey):
  165. bb.fatal("SWUPDATE_PRIVATE_KEY %s doesn't exist" % (privkey))
  166. signcmd = ["openssl", "dgst", "-sha256", "-sign", privkey] + get_pwd_file_args(d, 'SWUPDATE_PASSWORD_FILE') + ["-out", sw_desc_sig, sw_desc]
  167. elif signing == "CMS":
  168. cms_cert = d.getVar('SWUPDATE_CMS_CERT', True)
  169. if not cms_cert:
  170. bb.fatal("SWUPDATE_CMS_CERT is not set")
  171. if not os.path.exists(cms_cert):
  172. bb.fatal("SWUPDATE_CMS_CERT %s doesn't exist" % (cms_cert))
  173. cms_key = d.getVar('SWUPDATE_CMS_KEY', True)
  174. if not cms_key:
  175. bb.fatal("SWUPDATE_CMS_KEY isn't set")
  176. if not os.path.exists(cms_key):
  177. bb.fatal("SWUPDATE_CMS_KEY %s doesn't exist" % (cms_key))
  178. signcmd = ["openssl", "cms", "-sign", "-in", sw_desc, "-out", sw_desc_sig, "-signer", cms_cert, "-inkey", cms_key] + \
  179. get_pwd_file_args(d, 'SWUPDATE_PASSWORD_FILE') + ["-outform", "DER", "-nosmimecap", "-binary"]
  180. else:
  181. bb.fatal("Unrecognized SWUPDATE_SIGNING mechanism.")
  182. subprocess.run(' '.join(signcmd), shell=True, check=True)
  183. def swupdate_add_src_uri(d, list_for_cpio):
  184. import shutil
  185. s = d.getVar('S', True)
  186. fetch = bb.fetch2.Fetch([], d)
  187. # Add files listed in SRC_URI to the swu file
  188. for url in fetch.urls:
  189. local = fetch.localpath(url)
  190. filename = os.path.basename(local)
  191. aes_file = d.getVar('SWUPDATE_AES_FILE', True)
  192. if aes_file:
  193. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  194. if (filename != 'sw-description') and (os.path.isfile(local)):
  195. encrypted = (d.getVarFlag("SWUPDATE_IMAGES_ENCRYPTED", filename, True) or "")
  196. dst = os.path.join(s, "%s" % filename )
  197. if encrypted == '1':
  198. bb.note("Encryption requested for %s" %(filename))
  199. if not key or not iv:
  200. bb.fatal("Encryption required, but no key found")
  201. swupdate_encrypt_file(local, dst, key, iv)
  202. else:
  203. shutil.copyfile(local, dst)
  204. list_for_cpio.append(filename)
  205. def add_image_to_swu(d, deploydir, imagename, s, encrypt, list_for_cpio):
  206. import shutil
  207. src = os.path.join(deploydir, imagename)
  208. if not os.path.isfile(src):
  209. return False
  210. target_imagename = os.path.basename(imagename) # allow images in subfolders of DEPLOY_DIR_IMAGE
  211. dst = os.path.join(s, target_imagename)
  212. if encrypt == '1':
  213. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  214. bb.note("Encryption requested for %s" %(imagename))
  215. swupdate_encrypt_file(src, dst, key, iv)
  216. else:
  217. shutil.copyfile(src, dst)
  218. list_for_cpio.append(target_imagename)
  219. return True
  220. def swupdate_add_artifacts(d, list_for_cpio):
  221. import shutil
  222. # Search for images listed in SWUPDATE_IMAGES in the DEPLOY directory.
  223. images = (d.getVar('SWUPDATE_IMAGES', True) or "").split()
  224. deploydir = d.getVar('DEPLOY_DIR_IMAGE', True)
  225. imgdeploydir = d.getVar('SWUDEPLOYDIR', True)
  226. s = d.getVar('S', True)
  227. for image in images:
  228. fstypes = (d.getVarFlag("SWUPDATE_IMAGES_FSTYPES", image, True) or "").split()
  229. encrypted = (d.getVarFlag("SWUPDATE_IMAGES_ENCRYPTED", image, True) or "")
  230. if fstypes:
  231. noappend_machine = d.getVarFlag("SWUPDATE_IMAGES_NOAPPEND_MACHINE", image, True)
  232. if noappend_machine == "0": # Search for a file explicitly with MACHINE
  233. imagebases = [ image + '-' + d.getVar('MACHINE', True) ]
  234. elif noappend_machine == "1": # Search for a file explicitly without MACHINE
  235. imagebases = [ image ]
  236. else: # None, means auto mode. Just try to find an image file with MACHINE or without MACHINE
  237. imagebases = [ image + '-' + d.getVar('MACHINE', True), image ]
  238. for fstype in fstypes:
  239. image_found = False
  240. for imagebase in imagebases:
  241. image_found = add_image_to_swu(d, deploydir, imagebase + fstype, s, encrypted, list_for_cpio)
  242. if image_found:
  243. break
  244. if not image_found:
  245. bb.fatal("swupdate cannot find image file: %s" % os.path.join(deploydir, imagebase + fstype))
  246. else: # Allow also complete entries like "image.ext4.gz" in SWUPDATE_IMAGES
  247. if not add_image_to_swu(d, deploydir, image, s, encrypted, list_for_cpio):
  248. bb.fatal("swupdate cannot find %s image file" % image)
  249. def swupdate_create_cpio(d, swudeploydir, list_for_cpio):
  250. s = d.getVar('S', True)
  251. os.chdir(s)
  252. updateimage = d.getVar('IMAGE_NAME', True) + '.swu'
  253. line = 'for i in ' + ' '.join(list_for_cpio) + '; do echo $i;done | cpio -ov -H crc > ' + os.path.join(swudeploydir, updateimage)
  254. os.system(line)
  255. os.chdir(swudeploydir)
  256. updateimage_link = d.getVar('IMAGE_LINK_NAME', True)
  257. if updateimage_link:
  258. updateimage_link += '.swu'
  259. if updateimage_link != updateimage:
  260. os.symlink(updateimage, updateimage_link)
  261. python do_swuimage () {
  262. import shutil
  263. list_for_cpio = ["sw-description"]
  264. workdir = d.getVar('WORKDIR', True)
  265. s = d.getVar('S', True)
  266. imgdeploydir = d.getVar('SWUDEPLOYDIR', True)
  267. shutil.copyfile(os.path.join(workdir, "sw-description"), os.path.join(s, "sw-description"))
  268. if d.getVar('SWUPDATE_SIGNING', True):
  269. list_for_cpio.append('sw-description.sig')
  270. # Add artifacts added via SRC_URI
  271. if not d.getVar('INHIBIT_SWUPDATE_ADD_SRC_URI', True):
  272. swupdate_add_src_uri(d, list_for_cpio)
  273. # Add artifacts set via SWUPDATE_IMAGES
  274. swupdate_add_artifacts(d, list_for_cpio)
  275. prepare_sw_description(d)
  276. swupdate_create_cpio(d, imgdeploydir, list_for_cpio)
  277. }