swupdate-common.bbclass 16 KB

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