swupdate-common.bbclass 16 KB

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