swupdate-common.bbclass 16 KB

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