Browse Source

Update with binary deserialization.

- Move programs to programs.js module.
master
lbeckman314 2 years ago
parent
commit
48e143ed34
12 changed files with 3840 additions and 1566 deletions
  1. 1
    0
      .#code.org
  2. 0
    17
      app.py
  3. 0
    22
      client-example.html
  4. BIN
      demo-logo.png
  5. 0
    211
      demo.js
  6. BIN
      demo.png
  7. 3543
    783
      package-lock.json
  8. 47
    33
      package.json
  9. 124
    45
      programs.js
  10. 0
    93
      server-xterm.js
  11. 125
    194
      server.js
  12. 0
    168
      tmp

+ 1
- 0
.#code.org View File

@@ -0,0 +1 @@
liam@void.1328

+ 0
- 17
app.py View File

@@ -1,17 +0,0 @@
import tornado.web
from tornado.ioloop import IOLoop
from terminado import TermSocket, UniqueTermManager

if __name__ == '__main__':
term_manager = UniqueTermManager(shell_command=['firejail', '--quiet', '--net=none', '--private', '--chroot=files/fire', '/usr/local/bin/devilish.out'])

handlers = [
(r"/websocket", TermSocket, {'term_manager': term_manager}),
(r"/()", tornado.web.StaticFileHandler, {'path':'index.html'}),
(r"/(.*)", tornado.web.StaticFileHandler, {'path':'.'}),
]
app = tornado.web.Application(handlers)
app.listen(8282)
IOLoop.current().start()


+ 0
- 22
client-example.html View File

@@ -1,22 +0,0 @@
<h1>Interactive Demo</h1>
<script src="demo.js"></script>
<pre id="info"></pre>
<div id="terminal">
<pre class="terminals" tabindex="0" contentEditable="true"></pre>
</div>
<script type="text/javascript">MYLIBRARY.init(["prime 10101"]);</script>


<style>
#terminal {
overflow: auto;
width: 100%;
height: 25em;
resize: both;
background-color: black;
color: white;
padding: 2%;
border: 1px dashed grey;
}
</style>


BIN
demo-logo.png View File


+ 0
- 211
demo.js View File

@@ -1,211 +0,0 @@
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket

//var WebSocket = require('ws')
//const readline = require('readline');


//process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;

// Create WebSocket connection.
const socket = new WebSocket('wss://liambeckman.com:8181');
//const socket = new WebSocket('https://liambeckman.com/demo/devilish');

const userPrompt = "devilish";

var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private

return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function() {
//alert('Hello World! :: ' + _args[0]);
//console.log('Hello World! :: ' + _args[0]);
return _args[0];
}
};
}());


document.addEventListener('DOMContentLoaded', function () {
let terminal = document.getElementById("terminal");
terminal.spellcheck = false;
console.log("terminal:", terminal);
console.log("Connecting to server...");
terminal.innerHTML = "Connecting...\n";
// Connection opened
socket.onopen = function (event) {
console.log("Success!");
//terminal.innerHTML += "OK\n";
//command = readline.question(": ");
console.log("Sending initial message to server.");
//terminal.innerHTML += "Sending initial message to server.\n";
terminal.innerHTML = "Press ENTER to blast off!\n\n";

let userPrompt = MYLIBRARY.helloWorld();

terminal.innerHTML += "> " + userPrompt;

//socket.send("devilish");

let message = "";
let messages = [];
let commands = [];
let commNum = 0;
let up = 0;
let down = 0;
let ctrl = false;
// Listen for messages
socket.onmessage = function(event) {
//console.log("MESSAGE:", event.data);
terminal.innerHTML += event.data;
message = event.data.toString();
console.log("MESSAGE:", message);
messages = message.split("\n");
terminal.scrollTop = terminal.scrollHeight;
console.log("MESSAGES:", messages);

console.log("COMMAND:", comm);
}

// https://stackoverflow.com/questions/22092762/how-to-detect-ctrlc-and-ctrlv-key-pressing-using-regular-expression/22092839
document.getElementById('terminal').addEventListener("keydown",function(e){
e = e || window.event;
var key = e.which || e.keyCode; // keyCode detection
var ctrl = e.ctrlKey ? e.ctrlKey : ((key === 17) ? true : false); // ctrl detection

if ( key == 76 && ctrl ) {
console.log("Ctrl + L Pressed !");
terminal.innerHTML = "> ";
event.preventDefault();
e.preventDefault();
terminal.focus();
}
else if ( key == 67 && ctrl ) {
console.log("Ctrl + C Pressed !");
//e.preventDefault();
//event.preventDefault();
socket.send("SIGINT");
terminal.innerHTML += "\n";
//terminal.innerHTML = terminal.innerHTML.replace(/.*$/ ,"> ");
}

else if ( key == 85 && ctrl ) {
console.log("Ctrl + U Pressed !");
e.preventDefault();
//event.preventDefault();
terminal.innerHTML = terminal.innerHTML.replace(/.*$/ ,"> ");
}

},false);


document.getElementById('terminal').onkeydown = function (event) {
let key = event.keyCode;
let lines = terminal.innerHTML.split("\n");

console.log("key:", key);

if (key == 8) {
console.log(lines[lines.length - 1].length);
if (lines[lines.length - 1].length <= 2) {
console.log("backspace detected");
event.preventDefault();
}
}

else if (key == 46) {
console.log("delete detected");
//terminal.innerHTML += "\n> ";
}

else if (key == 9) {
event.preventDefault();
terminal.innerHTML += "TAB detected";
terminal.innerHTML += "\n> ";
console.log("TAB detected");
//socket.send("TAB");
//terminal.innerHTML += "\n> ";
}


else if (key == 38) {
console.log("up arrow detected");
event.preventDefault();
if ((up - down) < commands.length && down <= up) {
up += 1;
console.log("up:", up);
console.log("down:", down);
console.log("commands.length:", commands.length);
terminal.innerHTML = terminal.innerHTML.replace(/.*$/ ,"> " + commands[commands.length - up + down]);
}
console.log("commands:", commands);
//terminal.innerHTML += "\n> ";
}

else if (key == 40) {
console.log("down arrow detected");
event.preventDefault();
if (down < up && (up - down) <= commands.length) {
down += 1;
console.log("up:", up);
console.log("down:", down);
if (down == up) {
terminal.innerHTML = terminal.innerHTML.replace(/.*$/ ,"> ");
}
else {
terminal.innerHTML = terminal.innerHTML.replace(/.*$/ ,"> " + commands[commands.length - up + down]);
}
}
console.log("commands:", commands);
//terminal.innerHTML += "\n> ";
}

else if (key == 13)
{
event.preventDefault();
terminal.innerHTML += "\n";
up = 0;
down = 0;
for (let i = 0; i < lines.length; i++)
{
//console.log(lines[i]);
}
console.log("message:", message);
comm = lines[lines.length-1];
//console.log("you entered:", comm);
console.log("messages.length:", messages.length);
if (messages.length > 0) {
comm = comm.substring(messages[messages.length - 1].length - 1);
}
//console.log("you entered:", comm);
comm = comm.replace(/([>:]+ *)/g, "");
comm = comm.replace(/^[ ]*/g, "");

console.log("you entered:", comm);
if (comm == "clear") {
event.preventDefault();
terminal.innerHTML = "> ";
commands[commNum] = comm;
commNum += 1;
}

else if (comm == "") {
event.preventDefault();
terminal.innerHTML += "\n> ";
}

else {
socket.send(comm);
commands[commNum] = comm;
commNum += 1;
}

terminal.scrollTop = terminal.scrollHeight;
}

}
}
});

BIN
demo.png View File


+ 3543
- 783
package-lock.json
File diff suppressed because it is too large
View File


+ 47
- 33
package.json View File

@@ -1,35 +1,49 @@
{
"name": "demo-lbeckman314",
"version": "1.0.0",
"description": "Hello world with express and node.js",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"nodemonConfig": {
"ignore": [
"/var/www/demo/programs/*",
"/var/www/demo/files/*"
]
},
"author": "OSU",
"license": "ISC",
"dependencies": {
"ansi_up": "^4.0.3",
"body-parser": "^1.13.3",
"exec": "^0.2.1",
"express": "^4.16.3",
"express-handlebars": "^2.0.1",
"express-session": "^1.15.6",
"fs": "0.0.1-security",
"https": "^1.0.0",
"mysql": "^2.8.0",
"prettier": "^1.15.3",
"prompt": "^1.0.0",
"readline": "^1.3.0",
"readline-sync": "^1.4.9",
"spawn-sync": "^2.0.0",
"ws": "^6.1.2",
"xterm": "^3.10.1"
}
"name": "demo-lbeckman314",
"version": "1.0.0",
"description": "Hello world with express and node.js",
"main": "app.js",
"scripts": {
"start": "nodemon -e js,ejs,json,scss,css,md index.js",
"test": "node test.js",
"dev": "webpack --config webpack.config.js --mode development",
"watch": "webpack --config webpack.config.js --mode development --watch",
"analyze": "webpack --config webpack.config.js --mode production --profile --json > stats.json",
"build": "webpack --config webpack.config.js --mode production"
},
"nodemonConfig": {
"ignore": [
"/var/www/demo/programs/*",
"/var/www/demo/files/*"
]
},
"author": "OSU",
"license": "ISC",
"dependencies": {
"ansi_up": "^4.0.3",
"autolinker": "^3.1.0",
"body-parser": "^1.13.3",
"bson": "^4.0.2",
"exec": "^0.2.1",
"express": "^4.16.3",
"express-handlebars": "^2.0.1",
"express-session": "^1.15.6",
"fs": "0.0.1-security",
"https": "^1.0.0",
"jquery": "^3.4.1",
"mysql": "^2.8.0",
"prettier": "^1.15.3",
"prompt": "^1.0.0",
"readline": "^1.3.0",
"readline-sync": "^1.4.9",
"spawn-sync": "^2.0.0",
"webpack": "^4.34.0",
"websocket": "^1.0.28",
"ws": "^6.2.1",
"xterm": "^3.10.1"
},
"devDependencies": {
"@fortawesome/fontawesome-free": "^5.9.0",
"webpack-cli": "^3.3.4"
}
}

+ 124
- 45
programs.js View File

@@ -1,23 +1,27 @@
const { spawn } = require('child_process');
const options = {
detached: true,
stdio: 'pipe'
};


const { spawn, exec } = require('child_process');
const programs = [];

class Program {

let child = spawn('ls', options);
child.unref();
child.stdin.setEncoding('utf-8');
child.stdout.setEncoding('utf-8');
constructor(name, command) {
this.name = name;
this.command = command;
this.error = null;
this.message = null;

this.child = spawn('ls', this.options);

this.options = {
detached: true,
stdio: 'pipe',
};

this.options_shell = {
detached: true,
stdio: 'pipe',
shell: true,
cwd: 'programs/wyeast',
};

programs.push(this);
}
echo(name, command) {
@@ -32,40 +36,40 @@ child.stdout.setEncoding('utf-8');
setError(message) {
this.error = message;
}

getMessage() {
return this.message;
}
setMessage(message) {
this.message = message;
}

}

var palindrome = new Program(
let palindrome = new Program(
["palindrome", "./palindrome"],
function() {
child = spawn('programs/palindrome.out', options);
return spawn('programs/palindrome.out', this.options);
});

var scheme = new Program(
let scheme = new Program(
["scheme"],
function() {
child = spawn('scheme48', options);
return spawn('scheme48', this.options);
});

var haskell = new Program(
let haskell = new Program(
["haskell"],
function() {
child = spawn('ghci', options);
return spawn('ghci', this.options);
});

var cat = new Program(
let cat = new Program(
["cat"],
function() {
child = spawn('cat', [`./files/${messages[1]}`], options);
return spawn('cat', [`./files/${commands[1]}`], this.options);
});

var ls = new Program(
let ls = new Program(
["ls"],
function() {
let list = "";
@@ -75,32 +79,34 @@ var ls = new Program(
for (let i = 0; i < files.length; i++) {
list += files[i] + "\n";
}
this.setMessage(list);

console.log('setting message to:', list);
return list;
//return this.getMessage();
//return spawn('ls', this.options);
});

var matriz = new Program(
let matriz = new Program(
["matriz", "./matriz"],
function() {
/*
for (i = 0; i < messages.length; i++) {
console.log(`!!: ${messages[i]}`);
}
*/
if (messages[3]) {
child = spawn('programs/matriz.sh', [ `${messages[1]}`, `./files/${messages[2]}`, `./files/${messages[3]}`], options);
for (i = 0; i < commands.length; i++) {
console.log(`!!: ${commands[i]}`);
}
*/
if (commands[3]) {
return spawn('programs/matriz.sh', [ `${commands[1]}`, `./files/${commands[2]}`, `./files/${commands[3]}`], this.options);
}
else {
console.log(`!!: ${messages[0]} ${messages[1]} ${messages[2]}`);
child = spawn('programs/matriz.sh', [ `${messages[1]}`, `./files/${messages[2]}`], options);
console.log(`!!: ${commands[0]} ${commands[1]} ${commands[2]}`);
return spawn('programs/matriz.sh', [ `${commands[1]}`, `./files/${commands[2]}`], this.options);
}
});

var prime = new Program(
let prime = new Program(
["prime", "./prime"],
function() {
if (messages[1] <= 1000000) {
child = spawn('programs/prime.out', [`${messages[1]}`], options);
if (commands[1] <= 1000000) {
return spawn('programs/prime.out', [`${commands[1]}`], this.options);
}

else {
@@ -108,29 +114,102 @@ var prime = new Program(
}
});

var withfeathers = new Program(
let withfeathers = new Program(
["withfeathers", "python withfeathers"],
function() {
child = spawn('python3', ['programs/withfeathers/main.py', `${messages[1]}`], options);
return spawn('python3', ['programs/withfeathers/main.py', `${commands[1]}`], this.options);
});

var devilish = new Program(
let devilish = new Program(
["devilish", "./devilish"],
function() {
child = spawn('firejail', ['--quiet', '--net=none', '--hostname=demonic', '--rlimit-nproc=100', '--rlimit-as=50000000', '--nice=10', '--private=/home/demo', '--private-tmp', '--chroot=/var/www/demo/files/fire', '/usr/local/bin/devilish.out'], options);
return spawn('firejail', ['--quiet', '--net=none', '--hostname=demonic', '--rlimit-nproc=100', '--rlimit-as=50000000', '--nice=10', '--private=/home/demo', '--private-tmp', '--chroot=/let/www/demo/files/fire', '/usr/local/bin/devilish.out'], this.options);
});

var zigzag_server = new Program(
let zigzag_server = new Program(
["zigzag-server"],
function() {
child = spawn('python3', ['-u', 'programs/zigzag/zigzag-server.py'], options);
return spawn('python3', ['-u', 'programs/zigzag/zigzag-server.py'], this.options);
});

var zigzag_client = new Program(
let zigzag_client = new Program(
["zigzag-client"],
function() {
child = spawn('programs/zigzag/zigzag-client.out', [`127.0.1.1`, `${messages[1]}`], options);
return spawn('programs/zigzag/zigzag-client.out', [`127.0.1.1`, `${commands[1]}`], this.options);
});

let wyeast = new Program(
["wyeast"],
function() {
return spawn('./buildworld && ./wyeast', this.options_shell);
});

let voy = new Program(
["voy"],
function() {
let args = [];
for (let i = 1; i < commands.length; i++) {
args.push(commands[i]);
}
return spawn('voy', args, this.options);
});

let python = new Program(
["python", "python3"],
function() {
let args = [];
for (let i = 1; i < commands.length; i++) {
args.push(commands[i]);
}
console.log('args:', args);
return spawn('python', args, this.options);
});

let javascript = new Program(
["javascript", "node"],
function() {
let args = [];
for (let i = 1; i < commands.length; i++) {
args.push(commands[i]);
}
console.log('args:', args);
return spawn('node', args, this.options);
});

let gpp = new Program(
["gpp"],
function() {
let args = [];
for (let i = 1; i < commands.length; i++) {
args.push(commands[i]);
}
console.log('args:', args);

return spawn(`g++ -o ${args[1]} ${args[1]}.cpp && ${args[1]}`, {
shell: true,
});
});

let gcc = new Program(
["gcc"],
function() {
let args = [];
for (let i = 1; i < commands.length; i++) {
args.push(commands[i]);
}
console.log('args:', args);

const run = `
gcc -o ${args[1]} ${args[1]}.c &&
while [ ! -f ${args[1]} ]; do
sleep 1
done;
${args[1]}
`;
console.log(run)
return spawn(run, {
shell: true,
});
});

module.exports = programs;
module.exports.child = child;

+ 0
- 93
server-xterm.js View File

@@ -1,93 +0,0 @@
const WebSocket = require('ws');
const https = require('https');
const fs = require('fs');

const server = require('./config.js');

const wss = new WebSocket.Server({ server });

console.log("Waiting for clients...");

wss.on('connection', function connection(ws) {
console.log("Client connected!");


const { spawn } = require('child_process');
const options = {
detached: true,
stdio: 'pipe'
};

//child = spawn('firejail', ['--quiet', '--net=none', '--private', '--chroot=files/fire', '/usr/local/bin/devilish.out'], options);
child = spawn('programs/devilish.out', options);
child.unref();
child.stdin.setEncoding('utf-8');
child.stdout.setEncoding('utf-8');

userPrompt = "> ";

var buffer = "";


child.stdout.on('data', (data) => {

let sendData = data.toString();

console.log(`stdout: ${data}`);
console.log("SENDING TO CLIENT:", data.toString());
//res += data.toString();
ws.send(sendData, function ack(error) {
console.error("ERROR:", error);
});
//return res;
//res = ""
});

child.stderr.on('data', (data) => {
console.log(`stdout: ${data}`);
//console.log("SENDING TO CLIENT:", data.toString());
//res += data.toString();
ws.send(data.toString(), function ack(error) {
console.error("ERROR:", error);
});
//return res;
//res = ""
});



child.on('close', (code) => {
console.log(`child process exited with code ${code}`);
first = true;
child.kill("SIGINT");
ws.send(userPrompt, function ack(error) {
console.error("ERROR:", error);
});
});




ws.on('message', function incoming(message) {
if (message.charCodeAt(0) == 13) {
console.log('buffer: %s', buffer);

console.log("writing to child:", buffer);
child.stdin.write(buffer + "\n");
//child.stdin.write("exit\n");
//child.stdin.end();

buffer = "";
}

else {
buffer += message;
console.log('received: %s', message);
}

});


});

server.listen(process.argv[2] || 8181);

+ 125
- 194
server.js View File

@@ -1,7 +1,11 @@
const WebSocket = require('ws');
const fs = require('fs');
const server = require('./config.js');
const WebSocket = require('ws');
const wss = new WebSocket.Server({ server });
const programs = require('./programs.js');
const BSON = require('bson');

// heartbeat interval (attempts to reconnect if connection is broken)
function noop() {}

function heartbeat() {
@@ -15,27 +19,15 @@ const interval = setInterval(function ping() {
ws.isAlive = false;
ws.ping(noop);
});
}, 30000);
}, 3000);


const wss = new WebSocket.Server({ server });
// reference to spawned child process.
// actions for child's stdout, stdin, stderr, close
// are handled below.
let child = programs[0].child;

console.log("Waiting for clients...");

const { spawn } = require('child_process');
const options = {
detached: true,
stdio: 'pipe'
};

const options_shell = {
detached: true,
stdio: 'pipe',
shell: true,
cwd: 'programs/wyeast'
};


server.listen(process.argv[2] || 8181);

wss.on('connection', function connection(ws) {
console.log("Client connected!");
@@ -44,162 +36,63 @@ wss.on('connection', function connection(ws) {
ws.isAlive = true;
ws.on('pong', heartbeat);

let child = spawn('ls', options);
child.unref();
child.stdin.setEncoding('utf-8');
child.stdout.setEncoding('utf-8');

files = ["m1", "m2"];
userPrompt = "> ";
let mode = "web";

const programs = [];
ws.on('message', async function incoming(message) {
let command = '';
let code = '';
let language = '';
let mode = '';

class Program {
constructor(name, command) {
this.name = name;
this.command = command;
this.error = null;
this.message = null;
programs.push(this);
}
echo(name, command) {
console.log(`My name is ${this.name} and my command is ${this.command}.`);
}
run(command) {
command();
}
getError() {
return this.error;
}
setError(message) {
this.error = message;
}
try {
console.log('message:', message);
message = BSON.deserialize(message);

getMessage() {
return this.message;
}
setMessage(message) {
this.message = message;
}
}

var palindrome = new Program(
["palindrome", "./palindrome"],
function() {
child = spawn('programs/palindrome.out', options);
});

var scheme = new Program(
["scheme"],
function() {
child = spawn('scheme48', options);
});

var haskell = new Program(
["haskell"],
function() {
child = spawn('ghci', options);
});

var cat = new Program(
["cat"],
function() {
child = spawn('cat', [`./files/${messages[1]}`], options);
});

var ls = new Program(
["ls"],
function() {
let list = "";
for (let i = 0; i < programs.length; i++) {
list += programs[i].name[0] + "\n";
}
for (let i = 0; i < files.length; i++) {
list += files[i] + "\n";
if (message.command) {
command = message.command;
}
this.setMessage(list);

});

var matriz = new Program(
["matriz", "./matriz"],
function() {
/*
for (i = 0; i < messages.length; i++) {
console.log(`!!: ${messages[i]}`);
}
*/
if (messages[3]) {
child = spawn('programs/matriz.sh', [ `${messages[1]}`, `./files/${messages[2]}`, `./files/${messages[3]}`], options);
if (message.code) {
code = message.code;
command = message.language;
mode = message.mode;
}
else {
console.log(`!!: ${messages[0]} ${messages[1]} ${messages[2]}`);
child = spawn('programs/matriz.sh', [ `${messages[1]}`, `./files/${messages[2]}`], options);
}
});
} catch(err) {
command = message;
}

var prime = new Program(
["prime", "./prime"],
function() {
if (messages[1] <= 1000000) {
child = spawn('programs/prime.out', [`${messages[1]}`], options);
//console.log('command:', command);
console.log('COMMAND:', command);

if (mode == 'code') {
let language = message.language;
let code = message.code;
file = `/tmp/tmp.${Math.random()}`;

switch (language) {
case 'python':
write(file, code);
command = `python3 ${file}`;
break;
case 'javascript':
write(file, code);
command = `node ${file}`;
break;
case 'clike':
write(file, code, '.c');
command = `gcc -o ${file} ${file}.c && ${file}`;
break;
}
}

else {
this.setError("Prime number must be less than or equal to 1000000.\n");
}
});

var withfeathers = new Program(
["withfeathers", "python withfeathers"],
function() {
child = spawn('python3', ['programs/withfeathers/main.py', `${messages[1]}`], options);
});

var devilish = new Program(
["devilish", "./devilish"],
function() {
child = spawn('firejail', ['--quiet', '--net=none', '--hostname=demonic', '--rlimit-nproc=100', '--rlimit-as=50000000', '--nice=10', '--private=/home/demo', '--private-tmp', '--chroot=/var/www/demo/files/fire', '/usr/local/bin/devilish.out'], options);
});

var zigzag_server = new Program(
["zigzag-server"],
function() {
child = spawn('python3', ['-u', 'programs/zigzag/zigzag-server.py'], options);
});

var zigzag_client = new Program(
["zigzag-client"],
function() {
child = spawn('programs/zigzag/zigzag-client.out', [`127.0.1.1`, `${messages[1]}`], options);
});

var wyeast = new Program(
["wyeast"],
function() {
child = spawn('./buildworld && ./wyeast', options_shell);
});

var voy = new Program(
["voy"],
function() {
let args = [];
for (let i = 1; i < messages.length; i++) {
args.push(messages[i]);
}
console.log(args);
child = spawn('voy', args, options);
});

ws.on('message', function incoming(message) {
//console.log('received: %s', message);
if (message == "ping") {
if (command == "ping") {
ws.send("pong");
return;
}

else if (message == "close") {
else if (command == "close") {
ws.close();
return;
}
@@ -207,11 +100,9 @@ wss.on('connection', function connection(ws) {
if (first == true) {
first = false;

console.log(message);
if (message == ":(){ :|:& };:" || message == "sudo rm -rf /*") {
if (message == ":(){ :|:& };:" || command == "sudo rm -rf /*") {

first = true;

let song = "Daisy, Daisy,\n" +
"Give me your answer, do!\n" +
"I'm half crazy,\n" +
@@ -223,36 +114,46 @@ wss.on('connection', function connection(ws) {
ws.send(userPrompt, function ack(error) {
console.error("ERROR:", error);
});

}

else {

messages = message.split(" ");
for (i = 0; i < messages.length; i++) {
//console.log(messages[i]);
}

console.log('command:', command);
commands = command.split(" ");
let found = false;

// for all programs
for (i = 0; i < programs.length; i++) {
// for all names and aliases of each program
for (n = 0; n < programs[i].name.length; n++) {
if (messages[0] === programs[i].name[n]) {
console.log("calling:", programs[i].name[n]);
programs[i].command();
console.log("geterror:", programs[i].getError());
console.log("getMessage:", programs[i].getMessage());
// if the first word of the user command matches a name/alias
if (commands[0] === programs[i].name[n]) {
//console.log('child eval()', eval(programs[i].command)());
//console.log('typeof child eval()', typeof eval(programs[i].command)());
child = eval(programs[i].command)();
//console.log('typeof child:', typeof child);
if (typeof child == 'function') {
child = await child();
}
//console.log('new typeof child:', typeof child);
//console.log('new child:', child);

// emulates stderr
if (programs[i].getError()) {
ws.send(programs[i].getError());
ws.send(userPrompt);
first = true;
programs[i].setError(null);
}
if (programs[i].getMessage()) {

// emulates stdout
else if (programs[i].getMessage()) {
ws.send(programs[i].getMessage());
ws.send(userPrompt);
first = true;
programs[i].setMessage(null);
}


found = true;
break;
}
@@ -273,53 +174,83 @@ wss.on('connection', function connection(ws) {
}
}

child.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
//console.log('child:', child);
//console.log('typeof child:', typeof child);

// child is from "psuedo command" like "ls"
if (typeof child == 'string') {
let data = child;
ws.send(data, function ack(error) {
console.error("ERROR:", error);
});
});

child.stderr.on('data', (data) => {
console.log(`stdout: ${data}`);
ws.send(data.toString(), function ack(error) {
first = true;
ws.send(userPrompt, function ack(error) {
console.error("ERROR:", error);
});
});
}

// child is spawned process
else {
child.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
ws.send(data, function ack(error) {
console.error("ERROR:", error);
});
});

child.on('close', (code) => {
console.log(`child process exited with code ${code}`);
first = true;
child.kill("SIGINT");
ws.send(userPrompt, function ack(error) {
console.error("ERROR:", error);
child.stderr.on('data', (data) => {
console.log(`stdout: ${data}`);
ws.send(data.toString(), function ack(error) {
console.error("ERROR:", error);
});
});

child.on('close', (code) => {
console.log(`child process exited with code ${code}`);
first = true;
child.kill("SIGINT");
ws.send(userPrompt, function ack(error) {
console.error("ERROR:", error);
});
});
});
}

}

else {
if (message == "SIGINT") {
// signals
if (command == "SIGINT") {
ws.send("SIGINT received.\n", function ack(error) {
console.error("ERROR:", error);
});
child.kill("SIGINT");
first = true;
}
if (message == "SIGTSTP") {
if (command == "SIGTSTP") {
ws.send("SIGTSTP received.\n", function ack(error) {
console.error("ERROR:", error);
});
child.kill("SIGTSTP");
first = true;
}

// stdin
else {
console.log("writing to child:", message);
child.stdin.write(message + "\n");
console.log("writing to child:", command);
child.stdin.write(command + "\n");
}
}
});
});

server.listen(process.argv[2] || 8181);

function write(file, code, ext = '') {
let filename = file + ext;
fs.writeFile(filename, code, err => {
if(err) {
return console.log(err);
}
});
console.log(`wrote ${code} to ${filename}`);
}

+ 0
- 168
tmp View File

@@ -1,168 +0,0 @@
[
{
"city": "Portland",
"country": "United States",
"lon": "-122.67",
"lat": "45.52",
"id": 6782,
"population": 1207757,
"mbps": "25.86",
"beach": false,
"airport": true,
"elevation": 61,
"pollution": "27.61514529",
"palms": false,
"totalhomicides": "5.4",
"femalehomicides": "1.0",
"tempjan": 40,
"tempfeb": 60,
"tempmar": 78,
"tempapr": 99,
"tempmay": 131,
"tempjun": 165,
"tempjul": 192,
"tempaug": 193,
"tempsep": 165,
"tempoct": 117,
"tempnov": 73,
"tempdec": 43,
"precipjan": 167,
"precipfeb": 120,
"precipmar": 112,
"precipapr": 74,
"precipmay": 60,
"precipjun": 44,
"precipjul": 18,
"precipaug": 29,
"precipsep": 50,
"precipoct": 86,
"precipnov": 162,
"precipdec": 179,
"uvjan": 29,
"uvfeb": 43,
"uvmar": 72,
"uvapr": 106,
"uvmay": 72,
"uvjun": 151,
"uvjul": 151,
"uvaug": 136,
"uvsep": 99,
"uvoct": 61,
"uvnov": 35,
"uvdec": 26,
"purchasingpower": "1",
"povertyindex": 0,
"image": "https://d13k13wj6adfdf.cloudfront.net/urban_areas/portland-or-90f71ea149.jpg"
},
{
"city": "Portland",
"country": "United States",
"lon": "-70.24",
"lat": "43.67",
"id": 5446,
"population": 99504,
"mbps": "25.86",
"beach": true,
"airport": true,
"elevation": 1,
"pollution": "10.39126601",
"palms": false,
"totalhomicides": "5.4",
"femalehomicides": "1.0",
"tempjan": -58,
"tempfeb": -46,
"tempmar": 5,
"tempapr": 64,
"tempmay": 123,
"tempjun": 176,
"tempjul": 207,
"tempaug": 199,
"tempsep": 154,
"tempoct": 96,
"tempnov": 39,
"tempdec": -28,
"precipjan": 94,
"precipfeb": 88,
"precipmar": 102,
"precipapr": 102,
"precipmay": 92,
"precipjun": 86,
"precipjul": 78,
"precipaug": 80,
"precipsep": 83,
"precipoct": 101,
"precipnov": 125,
"precipdec": 111,
"uvjan": 22,
"uvfeb": 36,
"uvmar": 65,
"uvapr": 100,
"uvmay": 65,
"uvjun": 144,
"uvjul": 145,
"uvaug": 129,
"uvsep": 94,
"uvoct": 56,
"uvnov": 29,
"uvdec": 19,
"purchasingpower": "1",
"povertyindex": 0,
"image": null
},
{
"city": "Portland",
"country": "Australia",
"lon": "141.59",
"lat": "-38.33",
"id": 6742,
"population": 10325,
"mbps": "11.69",
"beach": true,
"airport": true,
"elevation": 4,
"pollution": "19.18740067",
"palms": false,
"totalhomicides": "0.9",
"femalehomicides": "0.7",
"tempjan": 172,
"tempfeb": 176,
"tempmar": 167,
"tempapr": 144,
"tempmay": 123,
"tempjun": 106,
"tempjul": 99,
"tempaug": 104,
"tempsep": 116,
"tempoct": 130,
"tempnov": 142,
"tempdec": 158,
"precipjan": 33,
"precipfeb": 27,
"precipmar": 44,
"precipapr": 66,
"precipmay": 84,
"precipjun": 97,
"precipjul": 111,
"precipaug": 110,
"precipsep": 81,
"precipoct": 68,
"precipnov": 54,
"precipdec": 45,
"uvjan": 207,
"uvfeb": 181,
"uvmar": 131,
"uvapr": 77,
"uvmay": 131,
"uvjun": 29,
"uvjul": 32,
"uvaug": 51,
"uvsep": 86,
"uvoct": 128,
"uvnov": 166,
"uvdec": 195,
"purchasingpower": "1.0894169998",
"povertyindex": 0,
"image": null
}
]


Loading…
Cancel
Save