This repository has been archived on 2022-10-24. You can view files and clone it, but cannot push or open issues or pull requests.
ctf10k-rpn/main.js
K0RB4K fe5c12b29c
done
Signed-off-by: K0RB4K <k0rb4k@k0rb4k.net>
2022-10-22 13:54:09 +02:00

60 lines
1.6 KiB
JavaScript

const Net = require('net');
const port = 8002
const host = "ctf10k.root-me.org"
const client = new Net.Socket
client.on('data', (data) => {
console.log("received data:\n", data.toString())
regex =/(?<equation>^\d+.*$)/m
let message = regex.exec(data.toString()).groups["equation"]
console.log("equation:", message)
let response = interpretRPN(message)
console.log("response:", response)
let buf = Buffer.from(response+"\n")
client.write(buf)
})
client.on('end', () => {
console.log("connection terminated by remote host")
})
client.connect({port: port, host: host}, () => {
console.log("connected")
})
function interpretRPN(message){
const operators = ['-', '+', 'x', '/']
let elements = message.split(' ')
for (let i = 0; i < elements.length; i++) {
if (operators.includes(elements[i])) {
let operation = elements.slice(i-2, i+1)
let result = computeOperation(operation)
elements.splice(i-2, 3, result)
i = 0
}
}
return elements.toString()
}
function computeOperation(operation) {
switch (operation[2]) {
case '-':
return BigInt(operation[0]) - BigInt(operation[1])
case 'x':
return BigInt(operation[0]) * BigInt(operation[1])
case '/':
return BigInt(operation[0]) / BigInt(operation[1])
case '+':
return BigInt(operation[0]) + BigInt(operation[1])
}
}
// const example = "994 611 + 357 733 + 82 543 - x x 740 + 136 x 996 +"
// console.log("response:", interpretRPN(example))