You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

win_verse.js 9.0KB

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