555
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

win_verse.js 7.1KB

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