deploy.py 3.49 KB
#-*- coding: utf-8 -*-
from flask import Flask, render_template, json, request, url_for
from werkzeug.datastructures import FileStorage
import os
import ipdb
from process import Process
import time, threading
from python_arptable import get_arp_table
import random
from enums import States, Table
import datetime

app = Flask(__name__)
retry_timer = 10
clean_timer = 20
prefix_lenght = 16
operation_timer = 86400

# folder for all messages
msgfolder = "msg/"

# database connection
process = Process("messages.db")

@app.route('/')
def main():
  return render_template('index.html')

@app.route('/key', methods = ['GET', 'POST'])
def key():
  f = open("rsa_key.pub", "r")
  key = f.read()
  f.close()
  return key

@app.route('/data', methods = ['POST'])
def data():
  prefix = newprefix()
  path = msgfolder + prefix + "/"
  os.mkdir(path)

  key = request.files.get('key')
  if key:
    request.files[file].save(path + "rand.key.enc")
    # decrypt random key with stored private key and store in prefix folder
    os.system("openssl rsautl -decrypt -inkey rsa_key.pri -in " + path + "rand.key.enc -out " + path + "rand.key")
    os.remove(path + "rand.key.enc")

  for file in request.files:
    # if key exists and this is not it
    if key and file != "key":
      request.files[file].save(filepath + ".enc")
      # decrypt file with decrypted random key and store in prefix folder
      os.system("openssl enc -d -aes-256-cbc -in " + filepath + ".enc -out " + filepath + " -pass file:" + path + "rand.key")
      os.remove(filepath + ".enc")
    else:
      request.files[file].save(path + request.files[file].filename)

  if key:
    os.remove(path + "rand.key")
  
  return str(process.datastore(path))

def newprefix():
  prefix = ""
  i = 0
  while i < prefix_lenght:
    range = random.randrange(3)
    if range == 0:
      prefix += chr(random.randrange(48,58))
    if range == 1:
      prefix += chr(random.randrange(65,91))
    if range == 2:
      prefix += chr(random.randrange(97,123))
    i += 1
  return prefix

@app.route('/msg', methods = ['POST'])
def msg():
  id = request.values['id']
  query = {
    Table.id : id,
    Table.serv : request.values['serv'],
    Table.dest : request.values['dest'],
    Table.type : request.values['type']
  }
  state = process.paramstore(query)
  return state

@app.route('/cons', methods = ['POST'])
def cons():
  id_query = request.form['id']
  row = process.lookup(id_query)
  if type(row) == str:  # error message
    return row 
  if row[Table.state] == States.delivered:
    os.system("rm -r" + row[Table.path])
  return str(row[Table.state])

def attempt():
  p = Process('messages.db')
  p.send()
  threading.Timer(retry_timer, attempt).start()

def clean():
  p = Process('messages.db')
  paths = p.paths()
  now = datetime.datetime.now()

  for folder in paths:
    mtime = os.path.getmtime(folder)
    # if the folder exists for more than a X seconds, erase it and its contents
    if int(now.strftime("%Y%m%d%H%M%S")) - int(time.strftime("%Y%m%d%H%M%S")) > operation_timer:
      os.system("rm -r " + folder)

  threading.Timer(clean_timer, clean).start()

if __name__ == "__main__":
  # generate keys
  os.system("openssl genrsa -out rsa_key.pri 4096") # private key
  os.system("openssl rsa -in rsa_key.pri -out rsa_key.pub -outform PEM -pubout") # public key
  # starts attempt daemon
  attempt()
  # starts cleaning daemon
  clean()
  # remove and recreate msg folder for cleanup purposes
  if os.path.exists(msgfolder):
    os.system("rm -r " + msgfolder)
  os.mkdir(msgfolder)
  app.run("0.0.0.0")