apply.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /**
  2. * @author oldj
  3. * @blog https://oldj.net
  4. *
  5. * try to apply hosts
  6. */
  7. 'use strict'
  8. const path = require('path')
  9. const exec = require('child_process').exec
  10. const io = require('./io')
  11. const {sys_host_path, work_path} = require('./paths')
  12. const crypto = require('crypto')
  13. const md5File = require('md5-file')
  14. const platform = process.platform
  15. let sudo_pswd = ''
  16. function needPswd(str) {
  17. str = str.toLowerCase()
  18. console.log('---')
  19. console.log(str)
  20. let keys = [
  21. 'Permission denied'
  22. , 'incorrect password'
  23. , 'Password:Sorry, try again.'
  24. ]
  25. return !!keys.find(k => str.includes(k.toLowerCase()))
  26. }
  27. function apply_Unix (content, callback) {
  28. let tmp_fn = path.join(work_path, 'tmp.txt')
  29. if (!content) {
  30. callback('no content')
  31. return
  32. }
  33. io.pWriteFile(tmp_fn, content)
  34. .then(() => {
  35. let cmd
  36. if (!sudo_pswd) {
  37. cmd = [
  38. `cat "${tmp_fn}" > ${sys_host_path}`
  39. , `rm -rf ${tmp_fn}`
  40. ].join(' && ')
  41. } else {
  42. sudo_pswd = sudo_pswd.replace(/'/g, '\\x27')
  43. cmd = [
  44. `echo '${sudo_pswd}' | sudo -S chmod 777 ${sys_host_path}`
  45. , `cat "${tmp_fn}" > ${sys_host_path}`
  46. , `echo '${sudo_pswd}' | sudo -S chmod 644 ${sys_host_path}`
  47. // , 'rm -rf ' + tmp_fn
  48. ].join(' && ')
  49. }
  50. return cmd
  51. })
  52. .then(cmd => {
  53. exec(cmd, function (error, stdout, stderr) {
  54. // command output is in stdout
  55. if (!error) {
  56. callback()
  57. return
  58. }
  59. callback(!sudo_pswd || needPswd(stdout + stderr) ? 'need_sudo' : error)
  60. })
  61. })
  62. }
  63. function apply_Win32 (content, callback) {
  64. // todo
  65. }
  66. function tryToApply (...args) {
  67. if (platform !== 'win32') {
  68. apply_Unix(...args)
  69. } else {
  70. apply_Win32(...args)
  71. }
  72. }
  73. module.exports = (cnt, pswd) => {
  74. if (pswd) {
  75. sudo_pswd = pswd
  76. }
  77. return new Promise((resolve, reject) => {
  78. let file_md5 = md5File.sync(sys_host_path)
  79. let cnt_md5 = crypto.createHash('md5').update(cnt).digest('hex')
  80. if (file_md5 === cnt_md5) {
  81. // 文件相同
  82. resolve()
  83. return
  84. }
  85. tryToApply(cnt, e => e ? reject(e) : resolve())
  86. //reject('need_sudo')
  87. })
  88. }