Commit 4256d873 authored by Luca Lamorte's avatar Luca Lamorte

Upload file TESTCASE1

parent 6cd57261
import osimport pikaimport tracebackimport logging VERSION = '0.0.1'COMPONENT_ID = "gui_tt" UPLOAD_FOLDER = './tmp'ALLOWED_EXTENSIONS = set(['json', 'pcap']) RABBIT_MQ_CONNECTED = False logger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG) try: AMQP_EXCHANGE = str(os.environ['AMQP_EXCHANGE'])except KeyError as e: print('couldnt import AMQP_EXCHANGE from environment') AMQP_EXCHANGE = "default" try: AMQP_URL = str(os.environ['AMQP_URL'])except KeyError as e: print('couldnt import AMQP_URL from environment') # TODO: REMOVE PERSONAL CONFIGURATION ## AMQP_URL = "amqp://guest:guest@localhost/" AMQP_URL = str(os.getenv('AMQP_URL', 'amqp://luca:luca@finterop1/session1')) def get_connection(AMQP_URL): try: print('Setting up AMQP connection... %s' % AMQP_URL) # setup AMQP connection return pika.BlockingConnection(pika.URLParameters(AMQP_URL)) except pika.exceptions.ConnectionClosed as cc: print(' AMQP cannot be established, is message broker up? \n More: %s' % traceback.format_exc()) return None def get_configuration(status = None): global RABBIT_MQ_CONNECTED if status: RABBIT_MQ_CONNECTED = status cfg = dict() cfg["url"] = AMQP_URL cfg["exchange"] = AMQP_EXCHANGE cfg["version"] = VERSION cfg["component"] = COMPONENT_ID cfg["connected"] = RABBIT_MQ_CONNECTED return cfg
\ No newline at end of file
import osimport pikaimport tracebackimport loggingimport errno VERSION = '0.0.1'COMPONENT_ID = "gui_tt" ALLOWED_EXTENSIONS = set(['json', 'pcap']) RABBIT_MQ_CONNECTED = False logger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG) project_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), os.pardir)) if '/testing_tool_gui' in project_dir: project_dir = os.path.abspath(os.path.join(project_dir, os.pardir)) TMPDIR = os.path.join(project_dir, 'tmp')DATADIR = os.path.join(project_dir, 'data') UPLOAD_FOLDER = TMPDIR # generate dirs for d in TMPDIR, DATADIR: try: os.makedirs(d) except OSError as e: if e.errno != errno.EEXIST: raise try: AMQP_EXCHANGE = str(os.environ['AMQP_EXCHANGE']) except KeyError as e: print('couldnt import AMQP_EXCHANGE from environment') AMQP_EXCHANGE = "default" try: AMQP_URL = str(os.environ['AMQP_URL']) except KeyError as e: print('couldnt import AMQP_URL from environment') # TODO: REMOVE PERSONAL CONFIGURATION ## AMQP_URL = "amqp://guest:guest@localhost/" AMQP_URL = str(os.getenv('AMQP_URL', 'amqp://luca:luca@finterop1/session1')) def get_connection(AMQP_URL): try: print('Setting up AMQP connection... %s' % AMQP_URL) # setup AMQP connection return pika.BlockingConnection(pika.URLParameters(AMQP_URL)) except pika.exceptions.ConnectionClosed as cc: print(' AMQP cannot be established, is message broker up? \n More: %s' % traceback.format_exc()) return None def get_configuration(status = None): global RABBIT_MQ_CONNECTED if status: RABBIT_MQ_CONNECTED = status cfg = dict() cfg["url"] = AMQP_URL cfg["exchange"] = AMQP_EXCHANGE cfg["version"] = VERSION cfg["component"] = COMPONENT_ID cfg["connected"] = RABBIT_MQ_CONNECTED return cfg
\ No newline at end of file
......
import base64
from flask import Flask
from flask import render_template, flash
......@@ -13,6 +14,7 @@ from testing_tool_gui.gui import *
from werkzeug.utils import secure_filename
amqp_connection = get_connection(AMQP_URL)
if amqp_connection:
......@@ -139,17 +141,17 @@ def configuration():
# else:
# return ""
@app.route('/upload', methods=['POST'])
def upload():
#publish_event(channel, MsgTestCaseStart())
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
......@@ -160,23 +162,24 @@ def upload():
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print("FILE %s stored in %s" % (filename, app.config['UPLOAD_FOLDER']))
return redirect(url_for('uploaded_file', filename=filename))
# do not dump into PCAP_DIR, coordinator puts the PCAPS there
with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), "rb") as pcapfile:
enc = base64.b64encode(pcapfile.read())
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
msg = MsgPrivacyAnalyze(
filename='%s' % filename,
value=enc.decode("utf-8")
)
logger.info("Message ready, PCAP bytes: \n" + repr(msg))
logger.info("Sending Request through AMQP interface ...")
publish_message(my_channel, msg)
else:
return "HAI MANDATO GET"
#return redirect("/", code=302)
return redirect("/", code=302)
......
......@@ -207,7 +207,6 @@ function showAll(){
function filterByRoutingKey(){
var routing_key = $('#filter_rk').val()
......
......@@ -8,6 +8,71 @@
* @param testcase
*/
// $('#pcap_form').submit(function(e){
// send_alert("ATTENZIONE", "ENTRATO")
// e.preventDefault();
// send_alert("NO REDIRECT", "ci sono riuscito")
// });
$(document).on('change', "#pcap_file", function(e){
if ($("#pcap_file").val() !== "")
$("#send_file_amqp").removeClass("fade");
else
$("#send_file_amqp").addClass("fade");
$("#file_path_display").html($("#pcap_file").val())
});
$(document).on('click', "#send_file_amqp", function(e) {
e.preventDefault();
var ext = $('#pcap_file').val().split('.').pop().toLowerCase();
if (ext !== 'pcap'){
send_alert("File not valid", "File with ."+ext+ " are not supported", 'danger')
return
}
$.ajax({
type: 'POST',
url: '/upload',
data: new FormData($('form')[0]),
processData: false, // important
contentType: false, // important
success: function(response) {
send_alert("Success","AMQP Message Sent! Analysis will start soon...")
},
error: function(error) {
send_alert("Fail",error , 'danger')
},
});
return false;
});
// function submit_pcap(e) {
// e.preventDefault();
// $.ajax({
// type: 'POST',
// url: '/upload_file',
// //data: new FormData($('form')[0]),
// processData: false, // important
// contentType: false, // important
// dataType : 'json',
// data: myFormData,
//
// success: function(response) {
// console.log(response);
// },
// error: function(error) {
// console.log(error);
// },
//
// });
// return false;
// }
function addTestCase(testcase){
// var index = parseInt(testcase)
// var title = ["Test Case1", "Test Case 2"]
......@@ -77,62 +142,65 @@ $(':file').on('change', function() {
// Also see .name, .type
});
function select_pcap(){
var filename = $("#pcap_file").val()
$("#upload-file-info").html(filename);
if (filename!=""){
var analyze = $("<button>").attr("type", "button").addClass("btn btn-danger")
analyze.attr("id", "analyze-pcap")
analyze.html("Analyze...")
analyze.click(function(){
$.ajax({
type: 'POST',
url: '/upload',
data: new FormData($('form')[0]),
enctype: 'multipart/form-data',
contentType: false,
cache: false,
processData: false,
async: false,
// // Custom XMLHttpRequest
// xhr: function() {
// var myXhr = $.ajaxSettings.xhr();
// if (myXhr.upload) {
// // For handling the progress of the upload
// myXhr.upload.addEventListener('progress', function(e) {
// if (e.lengthComputable) {
// $('progress').attr({
// value: e.loaded,
// max: e.total,
// });
// }
// } , false);
// }
// return myXhr;
// },
});
})
var cancel = $("<button>").attr("type", "button").addClass("btn btn-default")
cancel.html("Reset")
cancel.click(function(){
$("#cmq_area").html("");
$("#upload-file-info").html("");
});
$("#cmq_area").append(analyze).append(" ")
$("#cmq_area").append(cancel)
// function select_pcap(){
//
// var filename = $("#pcap_file").val()
// $("#upload-file-info").html(filename);
// if (filename!=""){
//
// var analyze = $("<button>").attr("type", "button").addClass("btn btn-danger")
// analyze.attr("id", "analyze-pcap")
// analyze.html("Analyze...")
// analyze.click(function(){
// $.ajax({
// type: 'POST',
// url: '/upload',
// data: new FormData($('form')[0]),
// enctype: 'multipart/form-data',
// contentType: false,
// cache: false,
// processData: false,
// async: false,
//
// // // Custom XMLHttpRequest
// // xhr: function() {
// // var myXhr = $.ajaxSettings.xhr();
// // if (myXhr.upload) {
// // // For handling the progress of the upload
// // myXhr.upload.addEventListener('progress', function(e) {
// // if (e.lengthComputable) {
// // $('progress').attr({
// // value: e.loaded,
// // max: e.total,
// // });
// // }
// // } , false);
// // }
// // return myXhr;
// // },
//
// });
//
//
// })
// var cancel = $("<button>").attr("type", "button").addClass("btn btn-default")
// cancel.html("Reset")
// cancel.click(function(){
// $("#cmq_area").html("");
// $("#upload-file-info").html("");
// });
//
// $("#cmq_area").append(analyze).append(" ")
// $("#cmq_area").append(cancel)
//
//
// }
// else{
// $("#cmq_area").html("")
// }
//
// }
}
else{
$("#cmq_area").html("")
}
}
......@@ -76,6 +76,7 @@ footer {
overflow: hidden;
display: inline-block;
}
.fileinput-button input {
position: absolute;
top: 0;
......
......@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css')}}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
......@@ -127,6 +127,7 @@
<li><a href="#">Get Status</a></li>
</ul>
</li>
<li><a href="coap.html">CoAP TT</a></li>
<li><a href="#">Orchestrator API</a></li>
<li><a href="http://doc.f-interop.eu/">Docs</a></li>
</ul>
......
......@@ -3,74 +3,37 @@
<span class="label label-primary"> Test Case 1</span>
</div>
<div class="col-md-11">
<p style="color: #000088">
User MUST provide the PCAP file of IUTs Conversation to check if there is any privacy issue.
</p>
<div class="row">
<!-- FORM -->
<!-- The file upload form used as target for the file upload widget -->
<form id="fileupload" method="POST" enctype="multipart/form-data">
<!-- Redirect browsers with JavaScript disabled to the origin page -->
<noscript><input type="hidden" name="redirect" value="/upload"></noscript>
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="row fileupload-buttonbar">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Preocedure to follow</h3>
</div>
<div class="panel-body">
<ul>
<li>User MUST provide the PCAP file of IUTs Conversation to check if there is any privacy issue.</li>
<li>Only Wireshark files (<strong>PCAP</strong>) are allowed in this demo (by default there is no file type restriction).</li>
</ul>
</div>
</div>
<!-- FORM -->
<!-- The file upload form used as target for the file upload widget -->
<form method="POST" enctype="multipart/form-data" method="post" action="/upload">
<div class="row">
<div class="col-lg-7">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<input type="file" name="files[]" multiple>
<span>Add file...</span>
<input type="file" name="file" id="pcap_file">
</span>
<button type="submit" class="btn btn-primary start">
<button class="btn btn-primary start fade" id="send_file_amqp">
<i class="glyphicon glyphicon-upload"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel upload</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="glyphicon glyphicon-trash"></i>
<span>Delete</span>
<span>Check Privacy Issues...</span>
</button>
<input type="checkbox" class="toggle">
<!-- The global file processing state -->
<span class="fileupload-process"></span>
</div>
<!-- The global progress state -->
<div class="col-lg-5 fileupload-progress">
<!-- The global progress bar -->
<div class="progress progress-striped active fade" role="progressbar" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-success" style="width:0%;"></div>
</div>
<!-- The extended global progress state -->
<div class="progress-extended">&nbsp;</div>
</div>
</div>
<!-- The table listing the files available for upload/download -->
<table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
</form>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Privacy Dumps Notes</h3>
</div>
<div class="panel-body">
<ul>
<li>The maximum file size for uploads in this demo is <strong>999 KB</strong> (default file size is unlimited).</li>
<li>Only image files (<strong>JPG, GIF, PNG</strong>) are allowed in this demo (by default there is no file type restriction).</li>
<li>Uploaded files will be deleted automatically after <strong>5 minutes or less</strong> (demo files are stored in memory).</li>
</ul>
</div>
<span id="file_path_display"></span>
</div>
</div>
</div>
<!-- END FORM -->
</div> <!-- col-md-3 -->
</div> <!-- row -->
</div> <!-- col-md-11 -->
</form>
</div>
</div>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment