swupdate-common.bbclass 17 KB

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