您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. const { any } = require('bbhverse');
  2. const fs = require('fs')
  3. var cli = require('./cliverse')
  4. var nodeShellExec = cli.nodeShellExec;
  5. var __isElevated = null;
  6. var shell_verse = {
  7. // getCommonTask is agnostic of whether we are running in an elevated shell or not. It runs in either case.
  8. getCommonTask( taskToRun ){ return ()=>{ return shell_verse.runTask(taskToRun) }}
  9. , runTask : ( taskToRun ) => {
  10. if (__isElevated) return shell_verse.elevatedRunner( taskToRun )
  11. else return shell_verse.runNonElevated( taskToRun )
  12. }
  13. , elevatedRunner( taskToRun ){
  14. // PB : TODO -- Should be called only when we are in an elevated shell that was already requested from an unelevated shell with a batch of tasks.
  15. try {
  16. var __runasresult = null;
  17. return taskToRun().then((r)=>{
  18. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  19. fs.writeFileSync('run.log', ', ' + JSON.stringify( { info : taskToRun.info, success: true }), { 'flag': 'a+' })
  20. fs.writeFileSync('run.done', 'success') // PB : TODO -- This should be done conditionally if we are running inproc.
  21. return __runasresult = r;
  22. })
  23. .catch((e) => {
  24. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  25. fs.writeFileSync('run.done', 'failure')
  26. console.error(e)
  27. })
  28. .finally(() => {
  29. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  30. })
  31. }
  32. catch (e) {
  33. console.error('Error Invalid command : ' + e)
  34. fs.writeFileSync('run.done', 'error')
  35. }
  36. finally {
  37. }
  38. }
  39. , getElevatedTask : function( taskToRun ){ return ()=>{ return shell_verse.runElevated(taskToRun) }}
  40. , runElevated : ( taskToRun ) => {
  41. // Let shell_verse decide whether to Elevate Out of Proc or In Proc
  42. // taskToRun by default is the launched command and args. Specially in windows out of proc.
  43. // taskToRun = taskToRun || (()=>{ return op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs) })
  44. if(taskToRun.processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  45. if (__isElevated) {
  46. return shell_verse.elevatedRunner(taskToRun)
  47. }
  48. else {
  49. console.log('Requesting Elevated Privileges');
  50. // requesteElevation is acutally request elevation and run. Both In Proc and Out of Proc.
  51. // Linux doesnt require elevation for most commands...
  52. return shell_verse.requestElevation(shell_verse.elevatedRunner, taskToRun)
  53. }
  54. }
  55. , runElevatedBatch( batchToRun ){
  56. // In windows we don't need to run each task. We hand over to another shell which in elevated state rebuilds the whole batch and runs.
  57. // Irrespective of the batch we just call runElevated once.
  58. if (__isElevated) {
  59. return any(batchToRun);
  60. }
  61. else {
  62. return this.runElevated(batchToRun[0])
  63. }
  64. }
  65. , getNonElevatedTask : function( taskToRun ){ return ()=>{ return shell_verse.runNonElevated(taskToRun) } }
  66. , runNonElevated : ( taskToRun ) => {
  67. // Let shell_verse decide whether to Elevate Out of Proc or In Proc
  68. if(__isElevated) {
  69. return Promise.resolve( 'Skipping regular task in elevated shell.' ) // Regular tasks unless marked as common tasks should not run in elevated shell...
  70. }
  71. else {
  72. // taskToRun by default is the launched command and args.
  73. // taskToRun = taskToRun || (()=>{ return op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs) })
  74. return taskToRun().then(r=>{
  75. taskToRun.statuslog.statuslog(null, taskToRun.info /*repo*/ )
  76. return r;
  77. }).catch((e) => {
  78. e.info = taskToRun.info;
  79. taskToRun.statuslog.statuslog(e);
  80. if(taskToRun.errHandler) throw taskToRun.errHandler(e)
  81. // console.error(e)
  82. throw e;
  83. }).finally(()=>{})
  84. }
  85. }
  86. , isElevated : ()=>{
  87. return acquireElevationState().then( ()=>{
  88. shell_verse.isElevated = () => {
  89. return Promise.resolve(__isElevated)
  90. }
  91. return shell_verse.isElevated()
  92. })
  93. }
  94. // , isElevationOutOfProc : ()=>{ return true }
  95. , acquireElevationState : () => {
  96. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  97. inherit: true
  98. // , shell: true
  99. , stdio: 'ignore'
  100. , env: process.env
  101. , title: `check privileged execution mode using "fsutil dirty query C:"`
  102. }).then((exitcode) => {
  103. console.log('Elevated')
  104. __isElevated = true;
  105. }).catch(() => {
  106. __isElevated = false;
  107. console.log('Not Elevated');
  108. }).finally(()=>{
  109. shell_verse.acquireElevationState = ()=> Promise.resolve(__isElevated);
  110. shell_verse.isElevated = () => { return Promise.resolve(__isElevated)}
  111. return __isElevated;
  112. })
  113. }
  114. , getTaskCheckExists : cli.createTask('getTaskCheckExists', 'where')
  115. , getbash : ()=>{ return "C:\\Program Files\\Git\\bin\\sh.exe" }
  116. , createJuntionOrLink : (dirOrFile, target, opts) =>{
  117. return nodeShellExec('mklink', ['/J', dirOrFile, target], opts).catch((e) => { console.error(e) })
  118. }
  119. , removeJuncionOrLink : ( junctionOrLink )=>{
  120. return nodeShellExec('rmdir', [junctionOrLink], { inherit: true, shell: true, env: process.env })
  121. }
  122. , requestElevation(elevatedRunner, taskToRun) {
  123. // PB : TODO -- Multiple parallel request elevations should be queued into a promise.
  124. var processedArgs = taskToRun.processedArgs, selectedinstance = taskToRun.selectedinstance , statuslog = taskToRun.statuslog
  125. // Wait for the runas to complete before we read it.
  126. try {
  127. fs.unlinkSync('run.done')
  128. fs.unlinkSync('run.log')
  129. }
  130. catch (e) { } //Ignore
  131. // Find node path to send to hta.
  132. return nodeShellExec('where', ['node']).then(r => {
  133. var namedArgs = [];
  134. console.log('result : ' + JSON.stringify(r))
  135. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  136. // PB : TODO -- Convert all the cli args back to string.
  137. var args = [`${selectedinstance.root}/.elxr/run-${taskToRun.runtimestamp}/windowselevate.hta`].concat(processedArgs._)
  138. namedArgs.length > 0 ? args = args.concat(namedArgs.join(' ')) : null;
  139. args.push('--runas=self');
  140. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  141. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  142. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  143. // console.dir(processedArgs._)
  144. // console.dir(namedArgs.join(' '))
  145. console.dir(args)
  146. // throw 'test'
  147. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  148. , {
  149. inherit: true
  150. , shell: true
  151. , env: taskToRun.ENV
  152. , runas: 'self'
  153. , title: `runas`
  154. }
  155. ).then(() => {
  156. // runas returned.
  157. try {
  158. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  159. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  160. runaslog.forEach((logEntry) => {
  161. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  162. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  163. })
  164. }
  165. catch (e) {
  166. // We must have a runas log
  167. statuslog.statuslog(e)
  168. console.error('Run log error probably was not created by runas : ' + e)
  169. }
  170. })
  171. .catch(err => console.error('Elevation failed : ' + err));
  172. })
  173. }
  174. }
  175. module.exports = shell_verse