package.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class Package < ApplicationModel
  3. @@root = Rails.root.to_s # rubocop:disable Style/ClassVars
  4. =begin
  5. verify if package is installed correctly
  6. package = Package.find(123)
  7. issues = package.verify
  8. returns:
  9. # if no issue exists
  10. nil
  11. # list of issues
  12. {
  13. 'path/to/file' => 'missing',
  14. 'path/to/file' => 'changed',
  15. }
  16. =end
  17. def verify
  18. # get package
  19. json_file = self.class._get_bin(name, version)
  20. package = JSON.parse(json_file)
  21. # verify installed files
  22. issues = {}
  23. package['files'].each do |file|
  24. if !File.exist?(file['location'])
  25. logger.error "File #{file['location']} is missing"
  26. issues[file['location']] = 'missing'
  27. next
  28. end
  29. content_package = Base64.decode64(file['content'])
  30. content_fs = self.class._read_file(file['location'])
  31. next if content_package == content_fs
  32. logger.error "File #{file['location']} is different"
  33. issues[file['location']] = 'changed'
  34. end
  35. return nil if issues.blank?
  36. issues
  37. end
  38. =begin
  39. install all packages located under auto_install/*.zpm
  40. Package.auto_install
  41. =end
  42. def self.auto_install
  43. path = "#{@@root}/auto_install/"
  44. return if !File.exist?(path)
  45. data = []
  46. Dir.foreach(path) do |entry|
  47. if entry.include?('.zpm') && entry !~ %r{^\.}
  48. data.push entry
  49. end
  50. end
  51. data.each do |file|
  52. install(file: "#{path}/#{file}")
  53. end
  54. data
  55. end
  56. =begin
  57. remove all linked files in application
  58. note: will not take down package migrations, use Package.unlink instead
  59. Package.unlink_all
  60. =end
  61. def self.unlink_all
  62. # link files
  63. Dir.glob("#{@@root}/**/*") do |entry|
  64. if File.symlink?(entry)
  65. logger.info "unlink: #{entry}"
  66. File.delete(entry)
  67. end
  68. backup_file = "#{entry}.link_backup"
  69. if File.exist?(backup_file)
  70. logger.info "Restore backup file of #{backup_file} -> #{entry}."
  71. File.rename(backup_file, entry)
  72. end
  73. end
  74. end
  75. # check if zpm is a package source repo
  76. def self._package_base_dir?(package_base_dir)
  77. package = false
  78. Dir.glob("#{package_base_dir}/*.szpm") do |entry|
  79. package = entry.sub(%r{^.*/(.+?)\.szpm$}, '\1')
  80. end
  81. if package == false
  82. raise "Can't link package, '#{package_base_dir}' is no package source directory!"
  83. end
  84. logger.debug { package.inspect }
  85. package
  86. end
  87. =begin
  88. execute migration down + unlink files
  89. Package.unlink('/path/to/src/extension')
  90. =end
  91. def self.unlink(package_base_dir)
  92. # check if zpm is a package source repo
  93. package = _package_base_dir?(package_base_dir)
  94. # migration down
  95. Package::Migration.migrate(package, 'reverse')
  96. # link files
  97. Dir.glob("#{package_base_dir}/**/*") do |entry|
  98. entry = entry.sub('//', '/')
  99. file = entry
  100. file = file.sub(%r{#{package_base_dir}}, '')
  101. dest = "#{@@root}/#{file}"
  102. if File.symlink?(dest.to_s)
  103. logger.info "Unlink file: #{dest}"
  104. File.delete(dest.to_s)
  105. end
  106. backup_file = "#{dest}.link_backup"
  107. if File.exist?(backup_file)
  108. logger.info "Restore backup file of #{backup_file} -> #{dest}."
  109. File.rename(backup_file, dest.to_s)
  110. end
  111. end
  112. end
  113. =begin
  114. link files
  115. Package.link('/path/to/src/extension')
  116. Migrations will not be executed because the the codebase was modified
  117. in the current process and is therefore inconsistent. This must be done
  118. subsequently in a separate step.
  119. =end
  120. def self.link(package_base_dir)
  121. # link files
  122. Dir.glob("#{package_base_dir}/**/*") do |entry|
  123. entry = entry.sub('//', '/')
  124. file = entry
  125. file = file.sub(%r{#{package_base_dir}}, '')
  126. file = file.sub(%r{^/}, '')
  127. # ignore files
  128. if file.start_with?('README')
  129. logger.info "NOTICE: Ignore #{file}"
  130. next
  131. end
  132. # get new file destination
  133. dest = "#{@@root}/#{file}"
  134. if File.directory?(entry.to_s) && !File.exist?(dest.to_s)
  135. logger.info "Create dir: #{dest}"
  136. FileUtils.mkdir_p(dest.to_s)
  137. end
  138. if File.file?(entry.to_s) && (File.file?(dest.to_s) && !File.symlink?(dest.to_s))
  139. backup_file = "#{dest}.link_backup"
  140. if File.exist?(backup_file)
  141. raise "Can't link #{entry} -> #{dest}, destination and .link_backup already exists!"
  142. end
  143. logger.info "Create backup file of #{dest} -> #{backup_file}."
  144. File.rename(dest.to_s, backup_file)
  145. end
  146. if File.file?(entry)
  147. if File.symlink?(dest.to_s)
  148. File.delete(dest.to_s)
  149. end
  150. logger.info "Link file: #{entry} -> #{dest}"
  151. File.symlink(entry.to_s, dest.to_s)
  152. end
  153. end
  154. end
  155. =begin
  156. install zpm package
  157. package = Package.install(file: '/path/to/package.zpm')
  158. or
  159. package = Package.install(string: zpm_as_string)
  160. returns
  161. package # record of newly created package
  162. Migrations will not be executed because the the codebase was modified
  163. in the current process and is therefore inconsistent. This must be done
  164. subsequently in a separate step.
  165. =end
  166. def self.install(data)
  167. if data[:file]
  168. json = _read_file(data[:file], true)
  169. package = JSON.parse(json)
  170. elsif data[:string]
  171. package = JSON.parse(data[:string])
  172. end
  173. # package meta data
  174. meta = {
  175. name: package['name'],
  176. version: package['version'],
  177. vendor: package['vendor'],
  178. state: 'uninstalled',
  179. created_by_id: 1,
  180. updated_by_id: 1,
  181. }
  182. # verify if package can get installed
  183. package_db = Package.find_by(name: meta[:name])
  184. if package_db
  185. if !data[:reinstall]
  186. if Gem::Version.new(package_db.version) == Gem::Version.new(meta[:version])
  187. raise "Package '#{meta[:name]}-#{meta[:version]}' already installed!"
  188. end
  189. if Gem::Version.new(package_db.version) > Gem::Version.new(meta[:version])
  190. raise "Newer version (#{package_db.version}) of package '#{meta[:name]}-#{meta[:version]}' already installed!"
  191. end
  192. end
  193. # uninstall files of old package
  194. uninstall(
  195. name: package_db.name,
  196. version: package_db.version,
  197. migration_not_down: true,
  198. reinstall: data[:reinstall],
  199. )
  200. end
  201. Transaction.execute do
  202. # store package
  203. if !data[:reinstall]
  204. package_db = Package.create(meta)
  205. Store.create!(
  206. object: 'Package',
  207. o_id: package_db.id,
  208. data: package.to_json,
  209. filename: "#{meta[:name]}-#{meta[:version]}.zpm",
  210. preferences: {},
  211. created_by_id: UserInfo.current_user_id || 1,
  212. )
  213. end
  214. # write files
  215. package['files'].each do |file|
  216. if !allowed_file_path?(file['location'])
  217. raise "Can't create file, because of not allowed file location: #{file['location']}!"
  218. end
  219. permission = file['permission'] || '644'
  220. content = Base64.decode64(file['content'])
  221. _write_file(file['location'], permission, content)
  222. end
  223. # update package state
  224. package_db.state = 'installed'
  225. package_db.save
  226. end
  227. package_db
  228. end
  229. =begin
  230. reinstall package
  231. package = Package.reinstall(package_name)
  232. returns
  233. package # record of newly created package
  234. =end
  235. def self.reinstall(package_name)
  236. package = Package.find_by(name: package_name)
  237. if !package
  238. raise "No such package '#{package_name}'"
  239. end
  240. file = _get_bin(package.name, package.version)
  241. install(string: file, reinstall: true)
  242. package
  243. end
  244. =begin
  245. uninstall package
  246. package = Package.uninstall(name: 'package', version: '0.1.1')
  247. or
  248. package = Package.uninstall(string: zpm_as_string)
  249. returns
  250. package # record of newly created package
  251. =end
  252. def self.uninstall(data)
  253. if data[:string]
  254. package = JSON.parse(data[:string])
  255. else
  256. json_file = _get_bin(data[:name], data[:version])
  257. package = JSON.parse(json_file)
  258. end
  259. # down migrations
  260. if !data[:migration_not_down]
  261. Package::Migration.migrate(package['name'], 'reverse')
  262. end
  263. package['files'].each do |file|
  264. permission = file['permission'] || '644'
  265. content = Base64.decode64(file['content'])
  266. _delete_file(file['location'], permission, content)
  267. end
  268. # delete package
  269. if !data[:reinstall]
  270. record = Package.find_by(
  271. name: package['name'],
  272. version: package['version'],
  273. )
  274. record.destroy
  275. end
  276. record
  277. end
  278. =begin
  279. execute all pending package migrations at once
  280. Package.migration_execute
  281. =end
  282. def self.migration_execute
  283. Package.all.each do |package|
  284. json_file = Package._get_bin(package.name, package.version)
  285. package = JSON.parse(json_file)
  286. Package::Migration.migrate(package['name'])
  287. end
  288. # sync package po files
  289. Translation.sync
  290. end
  291. def self._get_bin(name, version)
  292. package = Package.find_by(
  293. name: name,
  294. version: version,
  295. )
  296. if !package
  297. raise "No such package '#{name}' version '#{version}'"
  298. end
  299. list = Store.list(
  300. object: 'Package',
  301. o_id: package.id,
  302. )
  303. # find file
  304. if !list || !list.first
  305. raise "No such file in storage list #{name} #{version}"
  306. end
  307. if !list.first.content
  308. raise "No such file in storage #{name} #{version}"
  309. end
  310. list.first.content
  311. end
  312. def self._read_file(file, fullpath = false)
  313. location = case fullpath
  314. when false
  315. "#{@@root}/#{file}"
  316. when true
  317. file
  318. else
  319. "#{fullpath}/#{file}"
  320. end
  321. begin
  322. data = File.open(location, 'rb')
  323. contents = data.read
  324. rescue => e
  325. raise e
  326. end
  327. contents
  328. end
  329. def self._write_file(file, permission, data)
  330. location = "#{@@root}/#{file}"
  331. # rename existing file if not already the same file
  332. if File.exist?(location)
  333. content_fs = _read_file(file)
  334. if content_fs == data
  335. logger.debug { "NOTICE: file '#{location}' already exists, skip install" }
  336. return true
  337. end
  338. backup_location = "#{location}.save"
  339. logger.info "NOTICE: backup old file '#{location}' to #{backup_location}"
  340. File.rename(location, backup_location)
  341. end
  342. # check if directories need to be created
  343. directories = location.split '/'
  344. (0..(directories.length - 2)).each do |position|
  345. tmp_path = ''
  346. (1..position).each do |count|
  347. tmp_path = "#{tmp_path}/#{directories[count]}"
  348. end
  349. next if tmp_path == ''
  350. next if File.exist?(tmp_path)
  351. Dir.mkdir(tmp_path, 0o755)
  352. end
  353. # install file
  354. begin
  355. logger.info "NOTICE: install '#{location}' (#{permission})"
  356. file = File.new(location, 'wb')
  357. file.write(data)
  358. file.close
  359. File.chmod(permission.to_s.to_i(8), location)
  360. rescue => e
  361. raise e
  362. end
  363. true
  364. end
  365. def self._delete_file(file, _permission, _data)
  366. location = "#{@@root}/#{file}"
  367. # install file
  368. logger.info "NOTICE: uninstall '#{location}'"
  369. if File.exist?(location)
  370. File.delete(location)
  371. end
  372. # rename existing file
  373. backup_location = "#{location}.save"
  374. if File.exist?(backup_location)
  375. logger.info "NOTICE: restore old file '#{backup_location}' to #{location}"
  376. File.rename(backup_location, location)
  377. end
  378. true
  379. end
  380. def self.allowed_file_path?(file)
  381. file.exclude?('..') && file.exclude?('%2e%2e')
  382. end
  383. private_class_method :allowed_file_path?
  384. end