555
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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