mirror of
https://github.com/BlackLight/Snort_AIPreproc.git
synced 2025-02-17 16:03:48 +01:00
Improving the embedded web server
This commit is contained in:
parent
8305581fa2
commit
6a5815f2ee
12 changed files with 1661 additions and 48 deletions
1
TODO
1
TODO
|
@ -3,6 +3,7 @@ AVERAGE/HIGH PRIORITY:
|
||||||
======================
|
======================
|
||||||
|
|
||||||
- Web interface
|
- Web interface
|
||||||
|
- Function names (private functions with _ or __ ?)
|
||||||
- Bayesian network
|
- Bayesian network
|
||||||
- Modules for correlation coefficients
|
- Modules for correlation coefficients
|
||||||
- Code profiling
|
- Code profiling
|
||||||
|
|
|
@ -73,7 +73,7 @@ _AI_correlation_table_cleanup ()
|
||||||
*/
|
*/
|
||||||
|
|
||||||
PRIVATE void
|
PRIVATE void
|
||||||
_AI_print_correlated_alerts ( AI_alert_correlation *corr, FILE *fp )
|
_AI_correlated_alerts_to_dot ( AI_alert_correlation *corr, FILE *fp )
|
||||||
{
|
{
|
||||||
char src_addr1[INET_ADDRSTRLEN],
|
char src_addr1[INET_ADDRSTRLEN],
|
||||||
dst_addr1[INET_ADDRSTRLEN],
|
dst_addr1[INET_ADDRSTRLEN],
|
||||||
|
@ -130,8 +130,65 @@ _AI_print_correlated_alerts ( AI_alert_correlation *corr, FILE *fp )
|
||||||
timestamp2,
|
timestamp2,
|
||||||
corr->key.b->grouped_alerts_count
|
corr->key.b->grouped_alerts_count
|
||||||
);
|
);
|
||||||
} /* ----- end of function _AI_correlation_flow_to_file ----- */
|
} /* ----- end of function _AI_correlated_alerts_to_dot ----- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* \brief Recursively write the flow of correlated alerts to a .json file, ready for being rendered in the web interface
|
||||||
|
*/
|
||||||
|
|
||||||
|
PRIVATE void
|
||||||
|
_AI_correlated_alerts_to_json ()
|
||||||
|
{
|
||||||
|
unsigned int i = 0;
|
||||||
|
char json_file[1040] = { 0 };
|
||||||
|
FILE *fp;
|
||||||
|
AI_snort_alert *alert_iterator = NULL;
|
||||||
|
|
||||||
|
/* If there is no directory configured for the web interface, just exit */
|
||||||
|
if ( strlen ( config->webserv_dir ) == 0 )
|
||||||
|
return;
|
||||||
|
|
||||||
|
snprintf ( json_file, sizeof ( json_file ), "%s/correlation_graph.json", config->webserv_dir );
|
||||||
|
|
||||||
|
if ( !( fp = fopen ( json_file, "w" )))
|
||||||
|
{
|
||||||
|
AI_fatal_err ( "Unable to write on correlated_graph.json in htdocs directory", __FILE__, __LINE__ );
|
||||||
|
}
|
||||||
|
|
||||||
|
fprintf ( fp, "[\n" );
|
||||||
|
|
||||||
|
for ( alert_iterator = alerts; alert_iterator; alert_iterator = alert_iterator->next )
|
||||||
|
{
|
||||||
|
fprintf ( fp, "{\n"
|
||||||
|
"\t\"id\": %lu,\n"
|
||||||
|
"\t\"label\": \"%s\"",
|
||||||
|
alert_iterator->alert_id, alert_iterator->desc );
|
||||||
|
|
||||||
|
for ( i=0; i < alert_iterator->n_derived_alerts; i++ )
|
||||||
|
{
|
||||||
|
if ( i == 0 )
|
||||||
|
{
|
||||||
|
fprintf ( fp, ",\n\t\"connectedTo\": [\n" );
|
||||||
|
}
|
||||||
|
|
||||||
|
fprintf ( fp, "\t\t{ \"id\": %lu }%s\n",
|
||||||
|
alert_iterator->derived_alerts[i]->alert_id,
|
||||||
|
((i < alert_iterator->n_derived_alerts - 1) ? "," : ""));
|
||||||
|
|
||||||
|
if ( i == alert_iterator->n_derived_alerts - 1 )
|
||||||
|
{
|
||||||
|
fprintf ( fp, "\t]" );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fprintf ( fp, "\n}%s\n",
|
||||||
|
(alert_iterator->next ? "," : ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
fprintf ( fp, "]\n" );
|
||||||
|
fclose ( fp );
|
||||||
|
chmod ( json_file, 0644 );
|
||||||
|
} /* ----- end of function _AI_correlated_alerts_to_json ----- */
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* \brief Get the name of the function called by a pre-condition or post-condition predicate
|
* \brief Get the name of the function called by a pre-condition or post-condition predicate
|
||||||
|
@ -848,7 +905,7 @@ AI_alert_correlation_thread ( void *arg )
|
||||||
|
|
||||||
corr->key.a->derived_alerts[ corr->key.a->n_derived_alerts - 1 ] = corr->key.b;
|
corr->key.a->derived_alerts[ corr->key.a->n_derived_alerts - 1 ] = corr->key.b;
|
||||||
corr->key.b->parent_alerts [ corr->key.b->n_parent_alerts - 1 ] = corr->key.a;
|
corr->key.b->parent_alerts [ corr->key.b->n_parent_alerts - 1 ] = corr->key.a;
|
||||||
_AI_print_correlated_alerts ( corr, fp );
|
_AI_correlated_alerts_to_dot ( corr, fp );
|
||||||
|
|
||||||
if ( config->outdbtype != outdb_none )
|
if ( config->outdbtype != outdb_none )
|
||||||
{
|
{
|
||||||
|
@ -889,6 +946,16 @@ AI_alert_correlation_thread ( void *arg )
|
||||||
agclose ( g );
|
agclose ( g );
|
||||||
fclose ( fp );
|
fclose ( fp );
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/* If no database output is defined, then the alerts have no alert_id, so we cannot use the
|
||||||
|
* web interface for correlating them, as they have no unique identifier */
|
||||||
|
if ( config->outdbtype != outdb_none )
|
||||||
|
{
|
||||||
|
if ( strlen ( config->webserv_dir ) != 0 )
|
||||||
|
{
|
||||||
|
_AI_correlated_alerts_to_json ();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pthread_mutex_unlock ( &mutex );
|
pthread_mutex_unlock ( &mutex );
|
||||||
|
|
11
htdocs/graph.json
Normal file
11
htdocs/graph.json
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
[{
|
||||||
|
"id": 1,
|
||||||
|
"label": "test1",
|
||||||
|
"connectedTo": [
|
||||||
|
{ "id": 2 }
|
||||||
|
]
|
||||||
|
}, {
|
||||||
|
"id": 2,
|
||||||
|
"label": "test2"
|
||||||
|
}]
|
||||||
|
|
85
htdocs/index.html
Normal file
85
htdocs/index.html
Normal file
|
@ -0,0 +1,85 @@
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<script type="text/javascript" src="js/raphael-min.js"></script>
|
||||||
|
<script type="text/javascript" src="js/dracula_graffle.js"></script>
|
||||||
|
<script type="text/javascript" src="js/dracula_graph.js"></script>
|
||||||
|
<script type="text/javascript">
|
||||||
|
<!--
|
||||||
|
|
||||||
|
var redraw;
|
||||||
|
var width;
|
||||||
|
var height;
|
||||||
|
var layouter = null;
|
||||||
|
var renderer = null;
|
||||||
|
var json = [];
|
||||||
|
|
||||||
|
window.onload = function() {
|
||||||
|
var req = new XMLHttpRequest();
|
||||||
|
|
||||||
|
if ( navigator.appName.indexOf('Microsoft') != -1 )
|
||||||
|
{
|
||||||
|
width = (document.body.offsetWidth > 50) ?
|
||||||
|
document.body.offsetWidth - 50 : 50;
|
||||||
|
height = (document.body.offsetHeight > 50 ) ?
|
||||||
|
document.body.offsetHeight - 50 : 50;
|
||||||
|
} else {
|
||||||
|
width = (window.innerWidth > 50) ?
|
||||||
|
window.innerWidth - 50 : 50;
|
||||||
|
height = (window.innerHeight > 50) ?
|
||||||
|
window.innerHeight- 50 : 50;
|
||||||
|
}
|
||||||
|
|
||||||
|
req.open ( 'GET', 'http://localhost:7654/correlation_graph.json', true );
|
||||||
|
req.onreadystatechange = function() {
|
||||||
|
if ( req.readyState == 4 && req.status == 200 )
|
||||||
|
{
|
||||||
|
var g = new Graph();
|
||||||
|
var connections = [];
|
||||||
|
json = JSON.parse ( req.responseText );
|
||||||
|
|
||||||
|
for ( var i=0; i < json.length; i++ )
|
||||||
|
{
|
||||||
|
g.addNode ( json[i].id, { label: json[i].label });
|
||||||
|
|
||||||
|
if ( json[i].connectedTo )
|
||||||
|
{
|
||||||
|
for ( var j=0; j < json[i].connectedTo.length; j++ )
|
||||||
|
{
|
||||||
|
connections.push ({
|
||||||
|
"from": json[i].id,
|
||||||
|
"to" : json[i].connectedTo[j].id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for ( var i=0; i < connections.length; i++ )
|
||||||
|
{
|
||||||
|
g.addEdge ( connections[i].from, connections[i].to, { directed: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
var layouter = new Graph.Layout.Spring ( g );
|
||||||
|
layouter.layout();
|
||||||
|
|
||||||
|
var renderer = new Graph.Renderer.Raphael ( 'canvas', g, width, height );
|
||||||
|
renderer.draw();
|
||||||
|
|
||||||
|
redraw = function() {
|
||||||
|
layouter.layout();
|
||||||
|
renderer.draw();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
req.send ( null );
|
||||||
|
};
|
||||||
|
|
||||||
|
-->
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="canvas" style="border: 1px"></div>
|
||||||
|
<button id="redraw" onclick="redraw();">redraw</button>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
29
htdocs/js/Curry-1.0.1.js
Normal file
29
htdocs/js/Curry-1.0.1.js
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
/**
|
||||||
|
* Curry - Function currying
|
||||||
|
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
|
||||||
|
* Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
|
||||||
|
* Date: 10/4/2008
|
||||||
|
*
|
||||||
|
* @author Ariel Flesler
|
||||||
|
* @version 1.0.1
|
||||||
|
*/
|
||||||
|
|
||||||
|
function curry( fn ){
|
||||||
|
return function(){
|
||||||
|
var args = curry.args(arguments),
|
||||||
|
master = arguments.callee,
|
||||||
|
self = this;
|
||||||
|
|
||||||
|
return args.length >= fn.length ? fn.apply(self,args) : function(){
|
||||||
|
return master.apply( self, args.concat(curry.args(arguments)) );
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
curry.args = function( args ){
|
||||||
|
return Array.prototype.slice.call(args);
|
||||||
|
};
|
||||||
|
|
||||||
|
Function.prototype.curry = function(){
|
||||||
|
return curry(this);
|
||||||
|
};
|
414
htdocs/js/dracula_algorithms.js
Normal file
414
htdocs/js/dracula_algorithms.js
Normal file
|
@ -0,0 +1,414 @@
|
||||||
|
/*
|
||||||
|
* Various algorithms and data structures, licensed under the MIT-license.
|
||||||
|
* (c) 2010 by Johann Philipp Strathausen <strathausen@gmail.com>
|
||||||
|
* http://strathausen.eu
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
Path-finding algorithm Bellman-Ford
|
||||||
|
|
||||||
|
finds the shortest paths from one node to all nodes
|
||||||
|
- runs in O( |E| · |V| ), where E = edges and V = vertices (nodes)
|
||||||
|
- can run on graphs with negative edge weights as long as they do not have
|
||||||
|
any negative weight cycles
|
||||||
|
*/
|
||||||
|
function bellman_ford(g, source) {
|
||||||
|
|
||||||
|
/* STEP 1: initialisation */
|
||||||
|
for(var n in g.nodes)
|
||||||
|
g.nodes[n].distance = Infinity;
|
||||||
|
/* predecessors are implicitly null */
|
||||||
|
source.distance = 0;
|
||||||
|
g.snapShot("Initiallisation: Set all distances are infinite and all predecessors are null.");
|
||||||
|
|
||||||
|
/* STEP 2: relax each edge (this is at the heart of Bellman-Ford) */
|
||||||
|
/* repeat this for the number of nodes minus one */
|
||||||
|
for(var i = 1; i < g.nodes.length; i++)
|
||||||
|
/* for each edge */
|
||||||
|
for(var e in g.edges) {
|
||||||
|
var edge = g.edges[e];
|
||||||
|
if(edge.source.distance + edge.weight < edge.target.distance) {
|
||||||
|
g.snapShot("Relax edge between "+edge.source.id+" and "+edge.target.id+".");
|
||||||
|
edge.target.distance = edge.source.distance + edge.weight;
|
||||||
|
edge.target.predecessor = edge.source;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
g.snapShot("Ready.");
|
||||||
|
|
||||||
|
/* STEP 3: TODO Check for negative cycles */
|
||||||
|
/* For now we assume here that the graph does not contain any negative
|
||||||
|
weights cycles. (this is left as an excercise to the reader[tm]) */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
Path-finding algorithm Dijkstra
|
||||||
|
|
||||||
|
- worst-case running time is O( |E| + |V| · log |V| ) thus better than
|
||||||
|
Bellman-Ford, but cannot handle negative edge weights
|
||||||
|
*/
|
||||||
|
function dijkstra(g, source) {
|
||||||
|
/* initially, all distances are infinite and all predecessors are null */
|
||||||
|
for(var n in g.nodes)
|
||||||
|
g.nodes[n].distance = Infinity;
|
||||||
|
/* predecessors are implicitly null */
|
||||||
|
source.distance = 0;
|
||||||
|
var counter=0;
|
||||||
|
/* set of unoptimized nodes, sorted by their distance (but a Fibonacci heap
|
||||||
|
would be better) */
|
||||||
|
var q = new BinaryMinHeap(g.nodes, "distance");
|
||||||
|
|
||||||
|
var node;
|
||||||
|
/* get the node with the smallest distance */
|
||||||
|
/* as long as we have unoptimized nodes */
|
||||||
|
|
||||||
|
while(q.min()!=undefined) {
|
||||||
|
/* remove the latest */
|
||||||
|
node=q.extractMin();
|
||||||
|
node.optimized=true;
|
||||||
|
|
||||||
|
/* no nodes accessible from this one, should not happen */
|
||||||
|
if(node.distance == Infinity)
|
||||||
|
throw "Orphaned node!";
|
||||||
|
|
||||||
|
/* for each neighbour of node */
|
||||||
|
for(e in node.edges) {
|
||||||
|
if(node.edges[e].target.optimized)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
/* look for an alternative route */
|
||||||
|
var alt = node.distance + node.edges[e].weight;
|
||||||
|
|
||||||
|
/* update distance and route if a better one has been found */
|
||||||
|
if (alt < node.edges[e].target.distance) {
|
||||||
|
|
||||||
|
/* update distance of neighbour */
|
||||||
|
node.edges[e].target.distance = alt;
|
||||||
|
|
||||||
|
/* update priority queue */
|
||||||
|
q.heapify();
|
||||||
|
|
||||||
|
/* update path */
|
||||||
|
node.edges[e].target.predecessor = node;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Runs at worst in O(|V|³) and at best in Omega(|V|³) :-)
|
||||||
|
complexity Sigma(|V|²) */
|
||||||
|
/* This implementation is not yet ready for general use, but works with the
|
||||||
|
Dracula graph library. */
|
||||||
|
function floyd_warshall(g, source) {
|
||||||
|
|
||||||
|
/* Step 1: initialising empty path matrix (second dimension is implicit) */
|
||||||
|
var path = [];
|
||||||
|
var next = [];
|
||||||
|
var n = g.nodes.length;
|
||||||
|
|
||||||
|
/* construct path matrix, initialize with Infinity */
|
||||||
|
for(j in g.nodes) {
|
||||||
|
path[j] = [];
|
||||||
|
next[j] = [];
|
||||||
|
for(i in g.nodes)
|
||||||
|
path[j][i] = j == i ? 0 : Infinity;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* initialize path with edge weights */
|
||||||
|
for(e in g.edges)
|
||||||
|
path[g.edges[e].source.id][g.edges[e].target.id] = g.edges[e].weight;
|
||||||
|
|
||||||
|
/* Note: Usually, the initialisation is done by getting the edge weights
|
||||||
|
from a node matrix representation of the graph, not by iterating through
|
||||||
|
a list of edges as done here. */
|
||||||
|
|
||||||
|
/* Step 2: find best distances (the heart of Floyd-Warshall) */
|
||||||
|
for(k in g.nodes){
|
||||||
|
for(i in g.nodes) {
|
||||||
|
for(j in g.nodes)
|
||||||
|
if(path[i][j] > path[i][k] + path[k][j]) {
|
||||||
|
path[i][j] = path[i][k] + path[k][j];
|
||||||
|
/* Step 2.b: remember the path */
|
||||||
|
next[i][j] = k;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* Step 3: Path reconstruction */
|
||||||
|
function getPath(i, j) {
|
||||||
|
if(path[i][j] == Infinity)
|
||||||
|
throw "There is no path.";
|
||||||
|
var intermediate = next[i][j];
|
||||||
|
if(intermediate == undefined)
|
||||||
|
return null;
|
||||||
|
else
|
||||||
|
return getPath(i, intermediate)
|
||||||
|
.concat([intermediate])
|
||||||
|
.concat(getPath(intermediate, j));
|
||||||
|
}
|
||||||
|
// console&&console.log(path);
|
||||||
|
// console&&console.log(next);
|
||||||
|
|
||||||
|
/* TODO use the knowledge */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
A simple binary min-heap serving as a priority queue
|
||||||
|
- takes an array as the input, with elements having a key property
|
||||||
|
- elements will look like this:
|
||||||
|
{
|
||||||
|
key: "... key property ...",
|
||||||
|
value: "... element content ..."
|
||||||
|
}
|
||||||
|
- provides insert(), min(), extractMin() and heapify()
|
||||||
|
- example usage (e.g. via the Firebug console):
|
||||||
|
var x = {foo:20,hui:"bla"};
|
||||||
|
var a = new BinaryMinHeap([x,{foo:3},{foo:10},{foo:20},{foo:30},{foo:6},{foo:1},{foo:3}],"foo");
|
||||||
|
console.log(a.extractMin());
|
||||||
|
console.log(a.extractMin());
|
||||||
|
x.ma=0;
|
||||||
|
a.heapify(); // call this when key updated
|
||||||
|
console.log(a.extractMin());
|
||||||
|
console.log(a.extractMin());
|
||||||
|
- can also be used on a simple array, like [9,7,8,5]
|
||||||
|
*/
|
||||||
|
function BinaryMinHeap(array, key) {
|
||||||
|
|
||||||
|
/* Binary tree stored in an array, no need for a complicated data structure */
|
||||||
|
var tree = [];
|
||||||
|
|
||||||
|
var key = key || 'key';
|
||||||
|
|
||||||
|
/* Calculate the index of the parent or a child */
|
||||||
|
var parent = function(index) { return Math.floor((index - 1)/2); };
|
||||||
|
var right = function(index) { return 2 * index + 2; };
|
||||||
|
var left = function(index) { return 2 * index + 1; };
|
||||||
|
|
||||||
|
/* Helper function to swap elements with their parent
|
||||||
|
as long as the parent is bigger */
|
||||||
|
function bubble_up(i) {
|
||||||
|
var p = parent(i);
|
||||||
|
while((p >= 0) && (tree[i][key] < tree[p][key])) {
|
||||||
|
/* swap with parent */
|
||||||
|
tree[i] = tree.splice(p, 1, tree[i])[0];
|
||||||
|
/* go up one level */
|
||||||
|
i = p;
|
||||||
|
p = parent(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Helper function to swap elements with the smaller of their children
|
||||||
|
as long as there is one */
|
||||||
|
function bubble_down(i) {
|
||||||
|
var l = left(i);
|
||||||
|
var r = right(i);
|
||||||
|
|
||||||
|
/* as long as there are smaller children */
|
||||||
|
while(tree[l] && (tree[i][key] > tree[l][key]) || tree[r] && (tree[i][key] > tree[r][key])) {
|
||||||
|
|
||||||
|
/* find smaller child */
|
||||||
|
var child = tree[l] ? tree[r] ? tree[l][key] > tree[r][key] ? r : l : l : l;
|
||||||
|
|
||||||
|
/* swap with smaller child with current element */
|
||||||
|
tree[i] = tree.splice(child, 1, tree[i])[0];
|
||||||
|
|
||||||
|
/* go up one level */
|
||||||
|
i = child;
|
||||||
|
l = left(i);
|
||||||
|
r = right(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Insert a new element with respect to the heap property
|
||||||
|
1. Insert the element at the end
|
||||||
|
2. Bubble it up until it is smaller than its parent */
|
||||||
|
this.insert = function(element) {
|
||||||
|
|
||||||
|
/* make sure there's a key property */
|
||||||
|
(element[key] == undefined) && (element = {key:element});
|
||||||
|
|
||||||
|
/* insert element at the end */
|
||||||
|
tree.push(element);
|
||||||
|
|
||||||
|
/* bubble up the element */
|
||||||
|
bubble_up(tree.length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Only show us the minimum */
|
||||||
|
this.min = function() {
|
||||||
|
return tree.length == 1 ? undefined : tree[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Return and remove the minimum
|
||||||
|
1. Take the root as the minimum that we are looking for
|
||||||
|
2. Move the last element to the root (thereby deleting the root)
|
||||||
|
3. Compare the new root with both of its children, swap it with the
|
||||||
|
smaller child and then check again from there (bubble down)
|
||||||
|
*/
|
||||||
|
this.extractMin = function() {
|
||||||
|
var result = this.min();
|
||||||
|
|
||||||
|
/* move the last element to the root or empty the tree completely */
|
||||||
|
/* bubble down the new root if necessary */
|
||||||
|
(tree.length == 1) && (tree = []) || (tree[0] = tree.pop()) && bubble_down(0);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* currently unused, TODO implement */
|
||||||
|
this.changeKey = function(index, key) {
|
||||||
|
throw "function not implemented";
|
||||||
|
}
|
||||||
|
|
||||||
|
this.heapify = function() {
|
||||||
|
for(var start = Math.floor((tree.length - 2) / 2); start >= 0; start--) {
|
||||||
|
bubble_down(start);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//this.debug = function() {console&&console.log("----");for(i in tree){console&&console.log(tree[i].id,tree[i].distance);};}
|
||||||
|
/* insert the input elements one by one only when we don't have a key property (TODO can be done more elegant) */
|
||||||
|
// if (key=="key")
|
||||||
|
for(i in (array || []))
|
||||||
|
this.insert(array[i]);
|
||||||
|
// else {
|
||||||
|
// this.tree = array; // TODO there's an error here, maybe the array needs to be cloned or copied, because all reference is lost after this assignment
|
||||||
|
// this.heapify();
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
Quick Sort:
|
||||||
|
1. Select some random value from the array, the median.
|
||||||
|
2. Divide the array in three smaller arrays according to the elements
|
||||||
|
being less, equal or greater than the median.
|
||||||
|
3. Recursively sort the array containg the elements less than the
|
||||||
|
median and the one containing elements greater than the median.
|
||||||
|
4. Concatenate the three arrays (less, equal and greater).
|
||||||
|
5. One or no element is always sorted.
|
||||||
|
Note: This could be implemented more efficiently by using only one array.
|
||||||
|
*/
|
||||||
|
function quickSort(arr) {
|
||||||
|
/* recursion anchor: one element is always sorted */
|
||||||
|
if(arr.length <= 1) return arr;
|
||||||
|
/* randomly selecting some value */
|
||||||
|
var median = arr[Math.floor(Math.random() * arr.length)];
|
||||||
|
var arr1 = [], arr2 = [], arr3 = [];
|
||||||
|
for(var i in arr) {
|
||||||
|
arr[i] < median && arr1.push(arr[i]);
|
||||||
|
arr[i] == median && arr2.push(arr[i]);
|
||||||
|
arr[i] > median && arr3.push(arr[i]);
|
||||||
|
}
|
||||||
|
/* recursive sorting and assembling final result */
|
||||||
|
return quickSort(arr1).concat(arr2).concat(quickSort(arr3));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Selection Sort:
|
||||||
|
1. Select the minimum and remove it from the array
|
||||||
|
2. Sort the rest recursively
|
||||||
|
3. Return the minimum plus the sorted rest
|
||||||
|
4. An array with only one element is already sorted
|
||||||
|
*/
|
||||||
|
function selectionSort(arr) {
|
||||||
|
/* recursion anchor: one element is always sorted */
|
||||||
|
if(arr.length == 1) return arr;
|
||||||
|
var minimum = Infinity;
|
||||||
|
var index;
|
||||||
|
for(var i in arr) {
|
||||||
|
if(arr[i] < minimum) {
|
||||||
|
minimum = arr[i];
|
||||||
|
index = i; /* remember the minimum index for later removal */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* remove the minimum */
|
||||||
|
arr.splice(index, 1);
|
||||||
|
/* assemble result and sort recursively (could be easily done iteratively as well)*/
|
||||||
|
return [minimum].concat(selectionSort(arr));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Merge Sort:
|
||||||
|
1. Cut the array in half
|
||||||
|
2. Sort each of them recursively
|
||||||
|
3. Merge the two sorted arrays
|
||||||
|
4. An array with only one element is already sorted
|
||||||
|
|
||||||
|
*/
|
||||||
|
function mergeSort(arr) {
|
||||||
|
/* merges two sorted arrays into one sorted array */
|
||||||
|
function merge(a, b) {
|
||||||
|
/* result set */
|
||||||
|
var c = [];
|
||||||
|
/* as long as there are elements in the arrays to be merged */
|
||||||
|
while(a.length > 0 || b.length > 0){
|
||||||
|
/* are there elements to be merged, if yes, compare them and merge */
|
||||||
|
var n = a.length > 0 && b.length > 0 ? a[0] < b[0] ? a.shift() : b.shift() : b.length > 0 ? b.shift() : a.length > 0 ? a.shift() : null;
|
||||||
|
/* always push the smaller one onto the result set */
|
||||||
|
n != null && c.push(n);
|
||||||
|
}
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
/* this mergeSort implementation cuts the array in half, wich should be fine with randomized arrays, but introduces the risk of a worst-case scenario */
|
||||||
|
median = Math.floor(arr.length / 2);
|
||||||
|
var part1 = arr.slice(0, median); /* for some reason it doesn't work if inserted directly in the return statement (tried so with firefox) */
|
||||||
|
var part2 = arr.slice(median - arr.length);
|
||||||
|
return arr.length <= 1 ? arr : merge(
|
||||||
|
mergeSort(part1), /* first half */
|
||||||
|
mergeSort(part2) /* second half */
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Balanced Red-Black-Tree */
|
||||||
|
function RedBlackTree(arr) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
function BTree(arr) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
function NaryTree(n, arr) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Curry - Function currying
|
||||||
|
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
|
||||||
|
* Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
|
||||||
|
* Date: 10/4/2008
|
||||||
|
*
|
||||||
|
* @author Ariel Flesler
|
||||||
|
* @version 1.0.1
|
||||||
|
*/
|
||||||
|
|
||||||
|
function curry( fn ){
|
||||||
|
return function(){
|
||||||
|
var args = curry.args(arguments),
|
||||||
|
master = arguments.callee,
|
||||||
|
self = this;
|
||||||
|
|
||||||
|
return args.length >= fn.length ? fn.apply(self,args) : function(){
|
||||||
|
return master.apply( self, args.concat(curry.args(arguments)) );
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
curry.args = function( args ){
|
||||||
|
return Array.prototype.slice.call(args);
|
||||||
|
};
|
||||||
|
|
||||||
|
Function.prototype.curry = function(){
|
||||||
|
return curry(this);
|
||||||
|
};
|
105
htdocs/js/dracula_graffle.js
Normal file
105
htdocs/js/dracula_graffle.js
Normal file
|
@ -0,0 +1,105 @@
|
||||||
|
/**
|
||||||
|
* Originally grabbed from the official RaphaelJS Documentation
|
||||||
|
* http://raphaeljs.com/graffle.html
|
||||||
|
* Adopted (arrows) and commented by Philipp Strathausen http://blog.ameisenbar.de
|
||||||
|
* Licenced under the MIT licence.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Usage:
|
||||||
|
* connect two shapes
|
||||||
|
* parameters:
|
||||||
|
* source shape [or connection for redrawing],
|
||||||
|
* target shape,
|
||||||
|
* style with { fg : linecolor, bg : background color, directed: boolean }
|
||||||
|
* returns:
|
||||||
|
* connection { draw = function() }
|
||||||
|
*/
|
||||||
|
Raphael.fn.connection = function (obj1, obj2, style) {
|
||||||
|
var selfRef = this;
|
||||||
|
/* create and return new connection */
|
||||||
|
var edge = {/*
|
||||||
|
from : obj1,
|
||||||
|
to : obj2,
|
||||||
|
style : style,*/
|
||||||
|
draw : function() {
|
||||||
|
/* get bounding boxes of target and source */
|
||||||
|
var bb1 = obj1.getBBox();
|
||||||
|
var bb2 = obj2.getBBox();
|
||||||
|
var off1 = 0;
|
||||||
|
var off2 = 0;
|
||||||
|
/* coordinates for potential connection coordinates from/to the objects */
|
||||||
|
var p = [
|
||||||
|
{x: bb1.x + bb1.width / 2, y: bb1.y - off1}, /* NORTH 1 */
|
||||||
|
{x: bb1.x + bb1.width / 2, y: bb1.y + bb1.height + off1}, /* SOUTH 1 */
|
||||||
|
{x: bb1.x - off1, y: bb1.y + bb1.height / 2}, /* WEST 1 */
|
||||||
|
{x: bb1.x + bb1.width + off1, y: bb1.y + bb1.height / 2}, /* EAST 1 */
|
||||||
|
{x: bb2.x + bb2.width / 2, y: bb2.y - off2}, /* NORTH 2 */
|
||||||
|
{x: bb2.x + bb2.width / 2, y: bb2.y + bb2.height + off2}, /* SOUTH 2 */
|
||||||
|
{x: bb2.x - off2, y: bb2.y + bb2.height / 2}, /* WEST 2 */
|
||||||
|
{x: bb2.x + bb2.width + off2, y: bb2.y + bb2.height / 2} /* EAST 2 */
|
||||||
|
];
|
||||||
|
|
||||||
|
/* distances between objects and according coordinates connection */
|
||||||
|
var d = {}, dis = [];
|
||||||
|
|
||||||
|
/*
|
||||||
|
* find out the best connection coordinates by trying all possible ways
|
||||||
|
*/
|
||||||
|
/* loop the first object's connection coordinates */
|
||||||
|
for (var i = 0; i < 4; i++) {
|
||||||
|
/* loop the seond object's connection coordinates */
|
||||||
|
for (var j = 4; j < 8; j++) {
|
||||||
|
var dx = Math.abs(p[i].x - p[j].x),
|
||||||
|
dy = Math.abs(p[i].y - p[j].y);
|
||||||
|
if ((i == j - 4) || (((i != 3 && j != 6) || p[i].x < p[j].x) && ((i != 2 && j != 7) || p[i].x > p[j].x) && ((i != 0 && j != 5) || p[i].y > p[j].y) && ((i != 1 && j != 4) || p[i].y < p[j].y))) {
|
||||||
|
dis.push(dx + dy);
|
||||||
|
d[dis[dis.length - 1].toFixed(3)] = [i, j];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var res = dis.length == 0 ? [0, 4] : d[Math.min.apply(Math, dis).toFixed(3)];
|
||||||
|
/* bezier path */
|
||||||
|
var x1 = p[res[0]].x,
|
||||||
|
y1 = p[res[0]].y,
|
||||||
|
x4 = p[res[1]].x,
|
||||||
|
y4 = p[res[1]].y,
|
||||||
|
dx = Math.max(Math.abs(x1 - x4) / 2, 10),
|
||||||
|
dy = Math.max(Math.abs(y1 - y4) / 2, 10),
|
||||||
|
x2 = [x1, x1, x1 - dx, x1 + dx][res[0]].toFixed(3),
|
||||||
|
y2 = [y1 - dy, y1 + dy, y1, y1][res[0]].toFixed(3),
|
||||||
|
x3 = [0, 0, 0, 0, x4, x4, x4 - dx, x4 + dx][res[1]].toFixed(3),
|
||||||
|
y3 = [0, 0, 0, 0, y1 + dy, y1 - dy, y4, y4][res[1]].toFixed(3);
|
||||||
|
/* assemble path and arrow */
|
||||||
|
var path = ["M", x1.toFixed(3), y1.toFixed(3), "C", x2, y2, x3, y3, x4.toFixed(3), y4.toFixed(3)].join(",");
|
||||||
|
/* arrow */
|
||||||
|
if(style && style.directed) {
|
||||||
|
/* magnitude, length of the last path vector */
|
||||||
|
var mag = Math.sqrt((y4 - y3) * (y4 - y3) + (x4 - x3) * (x4 - x3));
|
||||||
|
/* vector normalisation to specified length */
|
||||||
|
var norm = function(x,l){return (-x*(l||5)/mag);};
|
||||||
|
/* calculate array coordinates (two lines orthogonal to the path vector) */
|
||||||
|
var arr = [
|
||||||
|
{x:(norm(x4-x3)+norm(y4-y3)+x4).toFixed(3), y:(norm(y4-y3)+norm(x4-x3)+y4).toFixed(3)},
|
||||||
|
{x:(norm(x4-x3)-norm(y4-y3)+x4).toFixed(3), y:(norm(y4-y3)-norm(x4-x3)+y4).toFixed(3)}
|
||||||
|
];
|
||||||
|
path = path + ",M"+arr[0].x+","+arr[0].y+",L"+x4+","+y4+",L"+arr[1].x+","+arr[1].y;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* applying path(s) */
|
||||||
|
edge.fg && edge.fg.attr({path:path})
|
||||||
|
|| (edge.fg = selfRef.path(path).attr({stroke: style && style.stroke || "#000", fill: "none"}).toBack());
|
||||||
|
edge.bg && edge.bg.attr({path:path})
|
||||||
|
|| style && style.fill && (edge.bg = style.fill.split && selfRef.path(path).attr({stroke: style.fill.split("|")[0], fill: "none", "stroke-width": style.fill.split("|")[1] || 3}).toBack());
|
||||||
|
/* setting label */
|
||||||
|
style && style.label
|
||||||
|
&& (edge.label && edge.label.attr({x:(x1+x4)/2, y:(y1+y4)/2})
|
||||||
|
|| (edge.label = selfRef.text((x1+x4)/2, (y1+y4)/2, style.label).attr({fill: "#000", "font-size":"14px"})));
|
||||||
|
// && selfRef.text(x4, y4, style.label).attr({stroke: style && style.stroke || "#fff", "font-weight":"bold", "font-size":"20px"})
|
||||||
|
// style && style.callback && style.callback(edge);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
edge.draw();
|
||||||
|
return edge;
|
||||||
|
};
|
||||||
|
//Raphael.prototype.set.prototype.dodo=function(){console.log("works");};
|
406
htdocs/js/dracula_graph.js
Normal file
406
htdocs/js/dracula_graph.js
Normal file
|
@ -0,0 +1,406 @@
|
||||||
|
/*
|
||||||
|
* Dracula Graph Layout and Drawing Framework 0.0.3alpha
|
||||||
|
* (c) 2010 Philipp Strathausen <strathausen@gmail.com>, http://strathausen.eu
|
||||||
|
*
|
||||||
|
* based on the Graph JavaScript framework, version 0.0.1
|
||||||
|
* (c) 2006 Aslak Hellesoy <aslak.hellesoy@gmail.com>
|
||||||
|
* (c) 2006 Dave Hoover <dave.hoover@gmail.com>
|
||||||
|
*
|
||||||
|
* Ported from Graph::Layouter::Spring in
|
||||||
|
* http://search.cpan.org/~pasky/Graph-Layderer-0.02/
|
||||||
|
* The algorithm is based on a spring-style layouter of a Java-based social
|
||||||
|
* network tracker PieSpy written by Paul Mutton E<lt>paul@jibble.orgE<gt>.
|
||||||
|
*
|
||||||
|
* This code is freely distributable under the terms of an MIT-style license.
|
||||||
|
* For details, see the Graph web site: http://dev.buildpatternd.com/trac
|
||||||
|
*
|
||||||
|
* Links:
|
||||||
|
*
|
||||||
|
* Graph Dracula JavaScript Framework:
|
||||||
|
* http://graphdracula.net
|
||||||
|
*
|
||||||
|
* Demo of the original applet:
|
||||||
|
* http://redsquirrel.com/dave/work/webdep/
|
||||||
|
*
|
||||||
|
* Mirrored original source code at snipplr:
|
||||||
|
* http://snipplr.com/view/1950/graph-javascript-framework-version-001/
|
||||||
|
*
|
||||||
|
* Original usage example:
|
||||||
|
* http://ajaxian.com/archives/new-javascriptcanvas-graph-library
|
||||||
|
*
|
||||||
|
/*--------------------------------------------------------------------------*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Graph
|
||||||
|
*/
|
||||||
|
var Graph = function() {
|
||||||
|
this.nodes = [];
|
||||||
|
this.nodelist = []; // nodes by index number, only used once TODO use only one node container
|
||||||
|
this.edges = [];
|
||||||
|
this.snapshots = []; // previous graph states
|
||||||
|
};
|
||||||
|
Graph.prototype = {
|
||||||
|
/*
|
||||||
|
* add a node
|
||||||
|
* @id the node's ID (string or number)
|
||||||
|
* @content (optional, dictionary) can contain any information that is
|
||||||
|
* being interpreted by the layout algorithm or the graph
|
||||||
|
* representation
|
||||||
|
*/
|
||||||
|
addNode: function(id, content) {
|
||||||
|
/* testing if node is already existing in the graph */
|
||||||
|
if(this.nodes[id] == undefined) {
|
||||||
|
this.nodes[id] = new Graph.Node(id, content || {"id" : id}); /* nodes indexed by node id */
|
||||||
|
this.nodelist.push(this.nodes[id]); /* node list indexed by numbers */
|
||||||
|
}
|
||||||
|
return this.nodes[id];
|
||||||
|
},
|
||||||
|
|
||||||
|
// TODO rename style to content
|
||||||
|
addEdge: function(source, target, style) {
|
||||||
|
var s = this.addNode(source);
|
||||||
|
var t = this.addNode(target);
|
||||||
|
var edge = { source: s, target: t, style: style, weight: style&&style.weight||1 }; // TODO tidy up here
|
||||||
|
s.edges.push(edge);
|
||||||
|
this.edges.push(edge);
|
||||||
|
/* add an edge back if graph undirected */
|
||||||
|
if(!style || !style.directed) {
|
||||||
|
var backedge = { source: t, target: s, style: style, weight : style&&style.weight||1, backedge : edge }; // TODO tidy up here
|
||||||
|
this.edges.push(backedge);
|
||||||
|
t.edges.push(backedge);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Preserve a copy of the graph state (nodes, positions, ...)
|
||||||
|
* @comment a comment describing the state
|
||||||
|
* @about a list with objects to be marked as significant in this state (TODO)
|
||||||
|
*/
|
||||||
|
snapShot: function(comment, about) {
|
||||||
|
// TODO get rid of the jQuery plugin dependence just for the deep copying
|
||||||
|
var graph = new Graph();
|
||||||
|
jQuery.extend(true, graph.nodes, this.nodes);
|
||||||
|
jQuery.extend(true, graph.nodelist, this.nodelist);
|
||||||
|
jQuery.extend(true, graph.edges, this.edges);
|
||||||
|
graph.snapShot = null;
|
||||||
|
this.snapshots.push({comment: comment, graph: graph});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Node
|
||||||
|
*/
|
||||||
|
Graph.Node = function(id, value){
|
||||||
|
value.id = id;
|
||||||
|
value.edges = [];
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
Graph.Node.prototype = {
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Renderer base class
|
||||||
|
*/
|
||||||
|
Graph.Renderer = {};
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Renderer implementation using RaphaelJS
|
||||||
|
*/
|
||||||
|
Graph.Renderer.Raphael = function(element, graph, width, height) {
|
||||||
|
this.width = width||400;
|
||||||
|
this.height = height||400;
|
||||||
|
var selfRef = this;
|
||||||
|
this.r = Raphael(element, this.width, this.height);
|
||||||
|
this.radius = 40; /* max dimension of a node */
|
||||||
|
this.graph = graph;
|
||||||
|
this.mouse_in = false;
|
||||||
|
|
||||||
|
/* TODO default node rendering function */
|
||||||
|
if(!this.graph.render) {
|
||||||
|
this.graph.render = function() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Dragging
|
||||||
|
*/
|
||||||
|
this.isDrag = false;
|
||||||
|
this.dragger = function (e) {
|
||||||
|
this.dx = e.clientX;
|
||||||
|
this.dy = e.clientY;
|
||||||
|
selfRef.isDrag = this;
|
||||||
|
this.set && this.set.animate({"fill-opacity": .1}, 200) && this.set.toFront();
|
||||||
|
e.preventDefault && e.preventDefault();
|
||||||
|
};
|
||||||
|
|
||||||
|
document.onmousemove = function (e) {
|
||||||
|
e = e || window.event;
|
||||||
|
if (selfRef.isDrag) {
|
||||||
|
var bBox = selfRef.isDrag.set.getBBox();
|
||||||
|
// TODO round the coordinates here (eg. for proper image representation)
|
||||||
|
var newX = e.clientX - selfRef.isDrag.dx + (bBox.x + bBox.width / 2);
|
||||||
|
var newY = e.clientY - selfRef.isDrag.dy + (bBox.y + bBox.height / 2);
|
||||||
|
/* prevent shapes from being dragged out of the canvas */
|
||||||
|
var clientX = e.clientX - (newX < 20 ? newX - 20 : newX > selfRef.width - 20 ? newX - selfRef.width + 20 : 0);
|
||||||
|
var clientY = e.clientY - (newY < 20 ? newY - 20 : newY > selfRef.height - 20 ? newY - selfRef.height + 20 : 0);
|
||||||
|
selfRef.isDrag.set.translate(clientX - selfRef.isDrag.dx, clientY - selfRef.isDrag.dy);
|
||||||
|
for (var i in selfRef.graph.edges) {
|
||||||
|
selfRef.graph.edges[i].connection && selfRef.graph.edges[i].connection.draw();
|
||||||
|
}
|
||||||
|
//selfRef.r.safari();
|
||||||
|
selfRef.isDrag.dx = clientX;
|
||||||
|
selfRef.isDrag.dy = clientY;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.onmouseup = function () {
|
||||||
|
selfRef.isDrag && selfRef.isDrag.set.animate({"fill-opacity": .6}, 500);
|
||||||
|
selfRef.isDrag = false;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
Graph.Renderer.Raphael.prototype = {
|
||||||
|
translate: function(point) {
|
||||||
|
return [
|
||||||
|
Math.round((point[0] - this.graph.layoutMinX) * this.factorX + this.radius),
|
||||||
|
Math.round((point[1] - this.graph.layoutMinY) * this.factorY + this.radius)
|
||||||
|
];
|
||||||
|
},
|
||||||
|
|
||||||
|
rotate: function(point, length, angle) {
|
||||||
|
var dx = length * Math.cos(angle);
|
||||||
|
var dy = length * Math.sin(angle);
|
||||||
|
return [point[0]+dx, point[1]+dy];
|
||||||
|
},
|
||||||
|
|
||||||
|
draw: function() {
|
||||||
|
this.factorX = (this.width - 2 * this.radius) / (this.graph.layoutMaxX - this.graph.layoutMinX);
|
||||||
|
this.factorY = (this.height - 2 * this.radius) / (this.graph.layoutMaxY - this.graph.layoutMinY);
|
||||||
|
for (i in this.graph.nodes) {
|
||||||
|
this.drawNode(this.graph.nodes[i]);
|
||||||
|
}
|
||||||
|
for (var i = 0; i < this.graph.edges.length; i++) {
|
||||||
|
this.drawEdge(this.graph.edges[i]);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
drawNode: function(node) {
|
||||||
|
var point = this.translate([node.layoutPosX, node.layoutPosY]);
|
||||||
|
node.point = point;
|
||||||
|
|
||||||
|
/* if node has already been drawn, move the nodes */
|
||||||
|
if(node.shape) {
|
||||||
|
var oBBox = node.shape.getBBox();
|
||||||
|
var opoint = [ oBBox.x + Math.round(oBBox.width / 2) , oBBox.y + Math.round(oBBox.height / 2) ];
|
||||||
|
node.shape.translate(point[0]-opoint[0], point[1]-opoint[1]);
|
||||||
|
this.r.safari();
|
||||||
|
return;
|
||||||
|
}/* else, draw new nodes */
|
||||||
|
var shape;
|
||||||
|
/* if a node renderer function is provided by the user, then use it */
|
||||||
|
if(node.render) {
|
||||||
|
shape = node.render(this.r, node);
|
||||||
|
/* or check for an ajax representation of the nodes */
|
||||||
|
} else if(node.shape) {
|
||||||
|
// TODO ajax representation
|
||||||
|
/* the default node drawing */
|
||||||
|
} else {
|
||||||
|
var color = Raphael.getColor();
|
||||||
|
shape = this.r.set().
|
||||||
|
push(this.r.ellipse(point[0], point[1], 30, 20).attr({fill: color, stroke: color, "stroke-width": 2})).
|
||||||
|
push(this.r.text(point[0], point[1] + 30, node.label || node.id));
|
||||||
|
}
|
||||||
|
shape.attr({"fill-opacity": .6});
|
||||||
|
/* reference to the node an element belongs to, needed for dragging all elements of a node */
|
||||||
|
shape.items.forEach(function(item){ item.set = shape; item.node.style.cursor = "move"; });
|
||||||
|
shape.mousedown(this.dragger);
|
||||||
|
node.shape = shape;
|
||||||
|
},
|
||||||
|
drawEdge: function(edge) {
|
||||||
|
/* if this edge already exists the other way around and is undirected */
|
||||||
|
if(edge.backedge)
|
||||||
|
return;
|
||||||
|
/* if edge already has been drawn, only refresh the edge */
|
||||||
|
edge.connection && edge.connection.draw();
|
||||||
|
if(!edge.connection) {
|
||||||
|
edge.style && edge.style.callback && edge.style.callback(edge);//TODO move this somewhere else
|
||||||
|
edge.connection = this.r.connection(edge.source.shape, edge.target.shape, edge.style);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Graph.Layout = {};
|
||||||
|
Graph.Layout.Spring = function(graph) {
|
||||||
|
this.graph = graph;
|
||||||
|
this.iterations = 500;
|
||||||
|
this.maxRepulsiveForceDistance = 6;
|
||||||
|
this.k = 2;
|
||||||
|
this.c = 0.01;
|
||||||
|
this.maxVertexMovement = 0.5;
|
||||||
|
};
|
||||||
|
Graph.Layout.Spring.prototype = {
|
||||||
|
layout: function() {
|
||||||
|
this.layoutPrepare();
|
||||||
|
for (var i = 0; i < this.iterations; i++) {
|
||||||
|
this.layoutIteration();
|
||||||
|
}
|
||||||
|
this.layoutCalcBounds();
|
||||||
|
},
|
||||||
|
|
||||||
|
layoutPrepare: function() {
|
||||||
|
for (i in this.graph.nodes) {
|
||||||
|
var node = this.graph.nodes[i];
|
||||||
|
node.layoutPosX = 0;
|
||||||
|
node.layoutPosY = 0;
|
||||||
|
node.layoutForceX = 0;
|
||||||
|
node.layoutForceY = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
layoutCalcBounds: function() {
|
||||||
|
var minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity;
|
||||||
|
|
||||||
|
for (i in this.graph.nodes) {
|
||||||
|
var x = this.graph.nodes[i].layoutPosX;
|
||||||
|
var y = this.graph.nodes[i].layoutPosY;
|
||||||
|
|
||||||
|
if(x > maxx) maxx = x;
|
||||||
|
if(x < minx) minx = x;
|
||||||
|
if(y > maxy) maxy = y;
|
||||||
|
if(y < miny) miny = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.graph.layoutMinX = minx;
|
||||||
|
this.graph.layoutMaxX = maxx;
|
||||||
|
this.graph.layoutMinY = miny;
|
||||||
|
this.graph.layoutMaxY = maxy;
|
||||||
|
},
|
||||||
|
|
||||||
|
layoutIteration: function() {
|
||||||
|
// Forces on nodes due to node-node repulsions
|
||||||
|
for (var i = 0; i < this.graph.nodelist.length; i++) {
|
||||||
|
var node1 = this.graph.nodelist[i];
|
||||||
|
for (var j = i + 1; j < this.graph.nodelist.length; j++) {
|
||||||
|
var node2 = this.graph.nodelist[j];
|
||||||
|
this.layoutRepulsive(node1, node2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Forces on nodes due to edge attractions
|
||||||
|
for (var i = 0; i < this.graph.edges.length; i++) {
|
||||||
|
var edge = this.graph.edges[i];
|
||||||
|
this.layoutAttractive(edge);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move by the given force
|
||||||
|
for (i in this.graph.nodes) {
|
||||||
|
var node = this.graph.nodes[i];
|
||||||
|
var xmove = this.c * node.layoutForceX;
|
||||||
|
var ymove = this.c * node.layoutForceY;
|
||||||
|
|
||||||
|
var max = this.maxVertexMovement;
|
||||||
|
if(xmove > max) xmove = max;
|
||||||
|
if(xmove < -max) xmove = -max;
|
||||||
|
if(ymove > max) ymove = max;
|
||||||
|
if(ymove < -max) ymove = -max;
|
||||||
|
|
||||||
|
node.layoutPosX += xmove;
|
||||||
|
node.layoutPosY += ymove;
|
||||||
|
node.layoutForceX = 0;
|
||||||
|
node.layoutForceY = 0;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
layoutRepulsive: function(node1, node2) {
|
||||||
|
var dx = node2.layoutPosX - node1.layoutPosX;
|
||||||
|
var dy = node2.layoutPosY - node1.layoutPosY;
|
||||||
|
var d2 = dx * dx + dy * dy;
|
||||||
|
if(d2 < 0.01) {
|
||||||
|
dx = 0.1 * Math.random() + 0.1;
|
||||||
|
dy = 0.1 * Math.random() + 0.1;
|
||||||
|
var d2 = dx * dx + dy * dy;
|
||||||
|
}
|
||||||
|
var d = Math.sqrt(d2);
|
||||||
|
if(d < this.maxRepulsiveForceDistance) {
|
||||||
|
var repulsiveForce = this.k * this.k / d;
|
||||||
|
node2.layoutForceX += repulsiveForce * dx / d;
|
||||||
|
node2.layoutForceY += repulsiveForce * dy / d;
|
||||||
|
node1.layoutForceX -= repulsiveForce * dx / d;
|
||||||
|
node1.layoutForceY -= repulsiveForce * dy / d;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
layoutAttractive: function(edge) {
|
||||||
|
var node1 = edge.source;
|
||||||
|
var node2 = edge.target;
|
||||||
|
|
||||||
|
var dx = node2.layoutPosX - node1.layoutPosX;
|
||||||
|
var dy = node2.layoutPosY - node1.layoutPosY;
|
||||||
|
var d2 = dx * dx + dy * dy;
|
||||||
|
if(d2 < 0.01) {
|
||||||
|
dx = 0.1 * Math.random() + 0.1;
|
||||||
|
dy = 0.1 * Math.random() + 0.1;
|
||||||
|
var d2 = dx * dx + dy * dy;
|
||||||
|
}
|
||||||
|
var d = Math.sqrt(d2);
|
||||||
|
if(d > this.maxRepulsiveForceDistance) {
|
||||||
|
d = this.maxRepulsiveForceDistance;
|
||||||
|
d2 = d * d;
|
||||||
|
}
|
||||||
|
var attractiveForce = (d2 - this.k * this.k) / this.k;
|
||||||
|
if(edge.attraction == undefined) edge.attraction = 1;
|
||||||
|
attractiveForce *= Math.log(edge.attraction) * 0.5 + 1;
|
||||||
|
|
||||||
|
node2.layoutForceX -= attractiveForce * dx / d;
|
||||||
|
node2.layoutForceY -= attractiveForce * dy / d;
|
||||||
|
node1.layoutForceX += attractiveForce * dx / d;
|
||||||
|
node1.layoutForceY += attractiveForce * dy / d;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
* usefull JavaScript extensions,
|
||||||
|
*/
|
||||||
|
//Array.prototype.forEach = function(f) {
|
||||||
|
// var l = this.length;
|
||||||
|
// for( var i = 0; i < l; i++) f(this[i]);
|
||||||
|
//};
|
||||||
|
|
||||||
|
function log(a) {console.log&&console.log(a);}
|
||||||
|
|
||||||
|
// this will eventually mess up array usage with for-in-loops
|
||||||
|
//Array.prototype.onEach = function(f, arg) {
|
||||||
|
// var l = this.length;
|
||||||
|
// for( var i = 0; i < l; i++) this[i][f]( arg );
|
||||||
|
//}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Raphael Tooltip Plugin
|
||||||
|
* - attaches an element as a tooltip to another element
|
||||||
|
*
|
||||||
|
* Usage example, adding a rectangle as a tooltip to a circle:
|
||||||
|
*
|
||||||
|
* paper.circle(100,100,10).tooltip(paper.rect(0,0,20,30));
|
||||||
|
*
|
||||||
|
* If you want to use more shapes, you'll have to put them into a set.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
Raphael.el.tooltip = function (tp) {
|
||||||
|
this.tp = tp;
|
||||||
|
this.tp.o = {x: 0, y: 0};
|
||||||
|
this.tp.hide();
|
||||||
|
this.hover(
|
||||||
|
function(event){
|
||||||
|
this.mousemove(function(event){
|
||||||
|
this.tp.translate(event.clientX -
|
||||||
|
this.tp.o.x,event.clientY - this.tp.o.y);
|
||||||
|
this.tp.o = {x: event.clientX, y: event.clientY};
|
||||||
|
});
|
||||||
|
this.tp.show().toFront();
|
||||||
|
},
|
||||||
|
function(event){
|
||||||
|
this.tp.hide();
|
||||||
|
this.unmousemove();
|
||||||
|
});
|
||||||
|
return this;
|
||||||
|
};
|
7
htdocs/js/raphael-min.js
vendored
Normal file
7
htdocs/js/raphael-min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
266
htdocs/js/seedrandom.js
Normal file
266
htdocs/js/seedrandom.js
Normal file
|
@ -0,0 +1,266 @@
|
||||||
|
// seedrandom.js
|
||||||
|
// Author: David Bau 3/11/2010
|
||||||
|
//
|
||||||
|
// Defines a method Math.seedrandom() that, when called, substitutes
|
||||||
|
// an explicitly seeded RC4-based algorithm for Math.random(). Also
|
||||||
|
// supports automatic seeding from local or network sources of entropy.
|
||||||
|
//
|
||||||
|
// Usage:
|
||||||
|
//
|
||||||
|
// <script src=http://davidbau.com/encode/seedrandom-min.js></script>
|
||||||
|
//
|
||||||
|
// Math.seedrandom('yipee'); Sets Math.random to a function that is
|
||||||
|
// initialized using the given explicit seed.
|
||||||
|
//
|
||||||
|
// Math.seedrandom(); Sets Math.random to a function that is
|
||||||
|
// seeded using the current time, dom state,
|
||||||
|
// and other accumulated local entropy.
|
||||||
|
// The generated seed string is returned.
|
||||||
|
//
|
||||||
|
// Math.seedrandom('yowza', true);
|
||||||
|
// Seeds using the given explicit seed mixed
|
||||||
|
// together with accumulated entropy.
|
||||||
|
//
|
||||||
|
// <script src="http://bit.ly/srandom-512"></script>
|
||||||
|
// Seeds using physical random bits downloaded
|
||||||
|
// from random.org.
|
||||||
|
//
|
||||||
|
// Examples:
|
||||||
|
//
|
||||||
|
// Math.seedrandom("hello"); // Use "hello" as the seed.
|
||||||
|
// document.write(Math.random()); // Always 0.5463663768140734
|
||||||
|
// document.write(Math.random()); // Always 0.43973793770592234
|
||||||
|
// var rng1 = Math.random; // Remember the current prng.
|
||||||
|
//
|
||||||
|
// var autoseed = Math.seedrandom(); // New prng with an automatic seed.
|
||||||
|
// document.write(Math.random()); // Pretty much unpredictable.
|
||||||
|
//
|
||||||
|
// Math.random = rng1; // Continue "hello" prng sequence.
|
||||||
|
// document.write(Math.random()); // Always 0.554769432473455
|
||||||
|
//
|
||||||
|
// Math.seedrandom(autoseed); // Restart at the previous seed.
|
||||||
|
// document.write(Math.random()); // Repeat the 'unpredictable' value.
|
||||||
|
//
|
||||||
|
// Notes:
|
||||||
|
//
|
||||||
|
// Each time seedrandom('arg') is called, entropy from the passed seed
|
||||||
|
// is accumulated in a pool to help generate future seeds for the
|
||||||
|
// zero-argument form of Math.seedrandom, so entropy can be injected over
|
||||||
|
// time by calling seedrandom with explicit data repeatedly.
|
||||||
|
//
|
||||||
|
// On speed - This javascript implementation of Math.random() is about
|
||||||
|
// 3-10x slower than the built-in Math.random() because it is not native
|
||||||
|
// code, but this is typically fast enough anyway. Seeding is more expensive,
|
||||||
|
// especially if you use auto-seeding. Some details (timings on Chrome 4):
|
||||||
|
//
|
||||||
|
// Our Math.random() - avg less than 0.002 milliseconds per call
|
||||||
|
// seedrandom('explicit') - avg less than 0.5 milliseconds per call
|
||||||
|
// seedrandom('explicit', true) - avg less than 2 milliseconds per call
|
||||||
|
// seedrandom() - avg about 38 milliseconds per call
|
||||||
|
//
|
||||||
|
// LICENSE (BSD):
|
||||||
|
//
|
||||||
|
// Copyright 2010 David Bau, all rights reserved.
|
||||||
|
//
|
||||||
|
// Redistribution and use in source and binary forms, with or without
|
||||||
|
// modification, are permitted provided that the following conditions are met:
|
||||||
|
//
|
||||||
|
// 1. Redistributions of source code must retain the above copyright
|
||||||
|
// notice, this list of conditions and the following disclaimer.
|
||||||
|
//
|
||||||
|
// 2. Redistributions in binary form must reproduce the above copyright
|
||||||
|
// notice, this list of conditions and the following disclaimer in the
|
||||||
|
// documentation and/or other materials provided with the distribution.
|
||||||
|
//
|
||||||
|
// 3. Neither the name of this module nor the names of its contributors may
|
||||||
|
// be used to endorse or promote products derived from this software
|
||||||
|
// without specific prior written permission.
|
||||||
|
//
|
||||||
|
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||||
|
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||||
|
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||||
|
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||||
|
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||||
|
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||||
|
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||||
|
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||||
|
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
//
|
||||||
|
/**
|
||||||
|
* All code is in an anonymous closure to keep the global namespace clean.
|
||||||
|
*
|
||||||
|
* @param {number=} overflow
|
||||||
|
* @param {number=} startdenom
|
||||||
|
*/
|
||||||
|
(function (pool, math, width, chunks, significance, overflow, startdenom) {
|
||||||
|
|
||||||
|
|
||||||
|
//
|
||||||
|
// seedrandom()
|
||||||
|
// This is the seedrandom function described above.
|
||||||
|
//
|
||||||
|
math['seedrandom'] = function seedrandom(seed, use_entropy) {
|
||||||
|
var key = [];
|
||||||
|
var arc4;
|
||||||
|
|
||||||
|
// Flatten the seed string or build one from local entropy if needed.
|
||||||
|
seed = mixkey(flatten(
|
||||||
|
use_entropy ? [seed, pool] :
|
||||||
|
arguments.length ? seed :
|
||||||
|
[new Date().getTime(), pool, window], 3), key);
|
||||||
|
|
||||||
|
// Use the seed to initialize an ARC4 generator.
|
||||||
|
arc4 = new ARC4(key);
|
||||||
|
|
||||||
|
// Mix the randomness into accumulated entropy.
|
||||||
|
mixkey(arc4.S, pool);
|
||||||
|
|
||||||
|
// Override Math.random
|
||||||
|
|
||||||
|
// This function returns a random double in [0, 1) that contains
|
||||||
|
// randomness in every bit of the mantissa of the IEEE 754 value.
|
||||||
|
|
||||||
|
math['random'] = function random() { // Closure to return a random double:
|
||||||
|
var n = arc4.g(chunks); // Start with a numerator n < 2 ^ 48
|
||||||
|
var d = startdenom; // and denominator d = 2 ^ 48.
|
||||||
|
var x = 0; // and no 'extra last byte'.
|
||||||
|
while (n < significance) { // Fill up all significant digits by
|
||||||
|
n = (n + x) * width; // shifting numerator and
|
||||||
|
d *= width; // denominator and generating a
|
||||||
|
x = arc4.g(1); // new least-significant-byte.
|
||||||
|
}
|
||||||
|
while (n >= overflow) { // To avoid rounding up, before adding
|
||||||
|
n /= 2; // last byte, shift everything
|
||||||
|
d /= 2; // right using integer math until
|
||||||
|
x >>>= 1; // we have exactly the desired bits.
|
||||||
|
}
|
||||||
|
return (n + x) / d; // Form the number within [0, 1).
|
||||||
|
};
|
||||||
|
|
||||||
|
// Return the seed that was used
|
||||||
|
return seed;
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
// ARC4
|
||||||
|
//
|
||||||
|
// An ARC4 implementation. The constructor takes a key in the form of
|
||||||
|
// an array of at most (width) integers that should be 0 <= x < (width).
|
||||||
|
//
|
||||||
|
// The g(count) method returns a pseudorandom integer that concatenates
|
||||||
|
// the next (count) outputs from ARC4. Its return value is a number x
|
||||||
|
// that is in the range 0 <= x < (width ^ count).
|
||||||
|
//
|
||||||
|
/** @constructor */
|
||||||
|
function ARC4(key) {
|
||||||
|
var t, u, me = this, keylen = key.length;
|
||||||
|
var i = 0, j = me.i = me.j = me.m = 0;
|
||||||
|
me.S = [];
|
||||||
|
me.c = [];
|
||||||
|
|
||||||
|
// The empty key [] is treated as [0].
|
||||||
|
if (!keylen) { key = [keylen++]; }
|
||||||
|
|
||||||
|
// Set up S using the standard key scheduling algorithm.
|
||||||
|
while (i < width) { me.S[i] = i++; }
|
||||||
|
for (i = 0; i < width; i++) {
|
||||||
|
t = me.S[i];
|
||||||
|
j = lowbits(j + t + key[i % keylen]);
|
||||||
|
u = me.S[j];
|
||||||
|
me.S[i] = u;
|
||||||
|
me.S[j] = t;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The "g" method returns the next (count) outputs as one number.
|
||||||
|
me.g = function getnext(count) {
|
||||||
|
var s = me.S;
|
||||||
|
var i = lowbits(me.i + 1); var t = s[i];
|
||||||
|
var j = lowbits(me.j + t); var u = s[j];
|
||||||
|
s[i] = u;
|
||||||
|
s[j] = t;
|
||||||
|
var r = s[lowbits(t + u)];
|
||||||
|
while (--count) {
|
||||||
|
i = lowbits(i + 1); t = s[i];
|
||||||
|
j = lowbits(j + t); u = s[j];
|
||||||
|
s[i] = u;
|
||||||
|
s[j] = t;
|
||||||
|
r = r * width + s[lowbits(t + u)];
|
||||||
|
}
|
||||||
|
me.i = i;
|
||||||
|
me.j = j;
|
||||||
|
return r;
|
||||||
|
};
|
||||||
|
// For robust unpredictability discard an initial batch of values.
|
||||||
|
// See http://www.rsa.com/rsalabs/node.asp?id=2009
|
||||||
|
me.g(width);
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// flatten()
|
||||||
|
// Converts an object tree to nested arrays of strings.
|
||||||
|
//
|
||||||
|
/** @param {Object=} result
|
||||||
|
* @param {string=} prop */
|
||||||
|
function flatten(obj, depth, result, prop) {
|
||||||
|
result = [];
|
||||||
|
if (depth && typeof(obj) == 'object') {
|
||||||
|
for (prop in obj) {
|
||||||
|
if (prop.indexOf('S') < 5) { // Avoid FF3 bug (local/sessionStorage)
|
||||||
|
try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result.length ? result : '' + obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// mixkey()
|
||||||
|
// Mixes a string seed into a key that is an array of integers, and
|
||||||
|
// returns a shortened string seed that is equivalent to the result key.
|
||||||
|
//
|
||||||
|
/** @param {number=} smear
|
||||||
|
* @param {number=} j */
|
||||||
|
function mixkey(seed, key, smear, j) {
|
||||||
|
seed += ''; // Ensure the seed is a string
|
||||||
|
smear = 0;
|
||||||
|
for (j = 0; j < seed.length; j++) {
|
||||||
|
key[lowbits(j)] =
|
||||||
|
lowbits((smear ^= key[lowbits(j)] * 19) + seed.charCodeAt(j));
|
||||||
|
}
|
||||||
|
seed = '';
|
||||||
|
for (j in key) { seed += String.fromCharCode(key[j]); }
|
||||||
|
return seed;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// lowbits()
|
||||||
|
// A quick "n mod width" for width a power of 2.
|
||||||
|
//
|
||||||
|
function lowbits(n) { return n & (width - 1); }
|
||||||
|
|
||||||
|
//
|
||||||
|
// The following constants are related to IEEE 754 limits.
|
||||||
|
//
|
||||||
|
startdenom = math.pow(width, chunks);
|
||||||
|
significance = math.pow(2, significance);
|
||||||
|
overflow = significance * 2;
|
||||||
|
|
||||||
|
//
|
||||||
|
// When seedrandom.js is loaded, we immediately mix a few bits
|
||||||
|
// from the built-in RNG into the entropy pool. Because we do
|
||||||
|
// not want to intefere with determinstic PRNG state later,
|
||||||
|
// seedrandom will not call math.random on its own again after
|
||||||
|
// initialization.
|
||||||
|
//
|
||||||
|
mixkey(math.random(), pool);
|
||||||
|
|
||||||
|
// End anonymous scope, and pass initial values.
|
||||||
|
})(
|
||||||
|
[], // pool: entropy pool starts empty
|
||||||
|
Math, // math: package containing random, pow, and seedrandom
|
||||||
|
256, // width: each RC4 output is 0 <= x < 256
|
||||||
|
6, // chunks: at least six RC4 outputs for each double
|
||||||
|
52 // significance: there are 52 significant digits in a double
|
||||||
|
);
|
10
htdocs/test.cgi
Executable file
10
htdocs/test.cgi
Executable file
|
@ -0,0 +1,10 @@
|
||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
echo "Content-Type: text/html"
|
||||||
|
echo
|
||||||
|
echo "<h1>LOL</h1>"
|
||||||
|
echo "Query string: <b>$QUERY_STRING</b><br>"
|
||||||
|
echo "Accept: <b>$HTTP_ACCEPT</b><br>"
|
||||||
|
echo "User-Agent: <b>$HTTP_USER_AGENT</b><br>"
|
||||||
|
echo "Client addr : <b>$REMOTE_ADDR</b><br>"
|
||||||
|
|
302
webserv.c
302
webserv.c
|
@ -36,6 +36,11 @@
|
||||||
"Content-Type: %s\r\n" \
|
"Content-Type: %s\r\n" \
|
||||||
"Content-Length: %u\r\n\r\n"
|
"Content-Length: %u\r\n\r\n"
|
||||||
|
|
||||||
|
#define HTTP_CGI_RESPONSE_HEADERS_FORMAT "%s %d %s\r\n" \
|
||||||
|
"Date: %s\r\n" \
|
||||||
|
"Server: %s\r\n" \
|
||||||
|
"Content-Length: %u\r\n"
|
||||||
|
|
||||||
#define HTTP_ERR_RESPONSE_FORMAT "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" \
|
#define HTTP_ERR_RESPONSE_FORMAT "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" \
|
||||||
"<html><head>\n" \
|
"<html><head>\n" \
|
||||||
"<title>%u %s</title>\n" \
|
"<title>%u %s</title>\n" \
|
||||||
|
@ -46,6 +51,11 @@
|
||||||
"<i>%s</i>\n" \
|
"<i>%s</i>\n" \
|
||||||
"</body></html>\n\n"
|
"</body></html>\n\n"
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
int sd;
|
||||||
|
struct sockaddr_in client;
|
||||||
|
} conn_info;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* \brief Escape a string to be used or included in an URL
|
* \brief Escape a string to be used or included in an URL
|
||||||
* \param str String to be escaped
|
* \param str String to be escaped
|
||||||
|
@ -173,20 +183,28 @@ __AI_webservlet_thread ( void *arg )
|
||||||
{
|
{
|
||||||
time_t ltime = time ( NULL );
|
time_t ltime = time ( NULL );
|
||||||
struct stat st;
|
struct stat st;
|
||||||
|
BOOL is_cgi = false;
|
||||||
|
|
||||||
FILE *sock = NULL,
|
FILE *sock = NULL,
|
||||||
*fp = NULL;
|
*fp = NULL,
|
||||||
|
*pipe = NULL;
|
||||||
|
|
||||||
int i,
|
int i,
|
||||||
*sd = (int*) arg,
|
http_response_len = 0,
|
||||||
|
sd = ((conn_info*) arg)->sd,
|
||||||
nlines = 0,
|
nlines = 0,
|
||||||
nmatches = 0,
|
nmatches = 0,
|
||||||
max_content_length = 0,
|
max_content_length = 0,
|
||||||
max_headers_length = 0,
|
max_headers_length = 0,
|
||||||
req_file_absolute_path_size = 0;
|
req_file_absolute_path_size = 0;
|
||||||
|
|
||||||
char *line = NULL,
|
char ch,
|
||||||
|
client_addr[INET_ADDRSTRLEN] = { 0 },
|
||||||
|
client_port[10] = { 0 },
|
||||||
|
*line = NULL,
|
||||||
*unescaped = NULL,
|
*unescaped = NULL,
|
||||||
|
*cgi_cmd = NULL,
|
||||||
|
*query_string = NULL,
|
||||||
*http_response = NULL,
|
*http_response = NULL,
|
||||||
*http_headers = NULL,
|
*http_headers = NULL,
|
||||||
*strtime = NULL,
|
*strtime = NULL,
|
||||||
|
@ -200,6 +218,16 @@ __AI_webservlet_thread ( void *arg )
|
||||||
max_content_length = strlen ( HTTP_ERR_RESPONSE_FORMAT ) + strlen ( config->webserv_banner ) + 1000;
|
max_content_length = strlen ( HTTP_ERR_RESPONSE_FORMAT ) + strlen ( config->webserv_banner ) + 1000;
|
||||||
max_headers_length = strlen ( HTTP_RESPONSE_HEADERS_FORMAT ) + strlen ( config->webserv_banner ) + 1000;
|
max_headers_length = strlen ( HTTP_RESPONSE_HEADERS_FORMAT ) + strlen ( config->webserv_banner ) + 1000;
|
||||||
|
|
||||||
|
/* Setting environment variables */
|
||||||
|
inet_ntop ( AF_INET, &(((conn_info*) arg)->client.sin_addr.s_addr), client_addr, INET_ADDRSTRLEN );
|
||||||
|
snprintf ( client_port, sizeof ( client_port ), "%d", htons (((conn_info*) arg)->client.sin_port) );
|
||||||
|
|
||||||
|
setenv ( "CLIENT_PROTOCOL", "HTTP", 1 );
|
||||||
|
setenv ( "DOCUMENT_ROOT", config->webserv_dir, 1 );
|
||||||
|
setenv ( "GATEWAY_INTERFACE", "CGI/1.1", 1 );
|
||||||
|
setenv ( "REMOTE_ADDR", client_addr, 1 );
|
||||||
|
setenv ( "REMOTE_PORT", client_port, 1 );
|
||||||
|
|
||||||
if ( !( http_response = (char*) alloca ( max_content_length )))
|
if ( !( http_response = (char*) alloca ( max_content_length )))
|
||||||
{
|
{
|
||||||
pthread_exit ((void*) 0);
|
pthread_exit ((void*) 0);
|
||||||
|
@ -212,7 +240,7 @@ __AI_webservlet_thread ( void *arg )
|
||||||
return (void*) 0;
|
return (void*) 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( !( sock = fdopen ( *sd, "r+" )))
|
if ( !( sock = fdopen ( sd, "r+" )))
|
||||||
{
|
{
|
||||||
pthread_exit ((void*) 0);
|
pthread_exit ((void*) 0);
|
||||||
return (void*) 0;
|
return (void*) 0;
|
||||||
|
@ -228,22 +256,41 @@ __AI_webservlet_thread ( void *arg )
|
||||||
|
|
||||||
for ( nlines=0; ( line = __AI_getline ( sock )); nlines++ )
|
for ( nlines=0; ( line = __AI_getline ( sock )); nlines++ )
|
||||||
{
|
{
|
||||||
if ( preg_match ( "^\\s*GET\\s+(/[^ ]*)\\s*(HTTP/[0-9]\\.[0-9])?", line, &matches, &nmatches ) > 0 )
|
if ( preg_match ( "^\\s*(GET|POST|HEAD)\\s+(/[^ \\?#]*)(\\?|#)?([^ ]+)?\\s*(HTTP/[0-9]\\.[0-9])?", line, &matches, &nmatches ) > 0 )
|
||||||
{
|
{
|
||||||
if ( strlen ( matches[1] ) > 0 )
|
setenv ( "REQUEST_METHOD", matches[0], 1 );
|
||||||
|
|
||||||
|
if ( !strcmp ( matches[2], "?" ))
|
||||||
{
|
{
|
||||||
strncpy ( http_ver, matches[1], sizeof ( http_ver ));
|
if ( strlen ( matches[3] ) > 0 )
|
||||||
|
{
|
||||||
|
query_string = strdup ( matches[3] );
|
||||||
|
setenv ( "QUERY_STRING", query_string, 1 );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( strlen ( matches[4] ) > 0 )
|
||||||
|
{
|
||||||
|
strncpy ( http_ver, matches[4], sizeof ( http_ver ));
|
||||||
} else {
|
} else {
|
||||||
strncpy ( http_ver, "HTTP/1.0", sizeof ( http_ver ));
|
strncpy ( http_ver, "HTTP/1.0", sizeof ( http_ver ));
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( !strcmp ( matches[0], "/" ))
|
setenv ( "SERVER_PROTOCOL", http_ver, 1 );
|
||||||
|
|
||||||
|
if ( !strcmp ( matches[1], "/" ))
|
||||||
{
|
{
|
||||||
free ( matches[0] );
|
free ( matches[1] );
|
||||||
matches[0] = strdup ( "/index.html" );
|
matches[1] = strdup ( "/index.html" );
|
||||||
}
|
}
|
||||||
|
|
||||||
snprintf ( req_file_absolute_path, req_file_absolute_path_size, "%s%s", config->webserv_dir, matches[0] );
|
setenv ( "DOCUMENT_URI", matches[1], 1 );
|
||||||
|
setenv ( "DOCUMENT_URL", matches[1], 1 );
|
||||||
|
setenv ( "REQUEST_URI", matches[1], 1 );
|
||||||
|
setenv ( "URI", matches[1], 1 );
|
||||||
|
setenv ( "URL", matches[1], 1 );
|
||||||
|
|
||||||
|
snprintf ( req_file_absolute_path, req_file_absolute_path_size, "%s%s", config->webserv_dir, matches[1] );
|
||||||
|
|
||||||
if ( strcmp ( http_ver, "HTTP/1.0" ) && strcmp ( http_ver, "HTTP/1.1" ))
|
if ( strcmp ( http_ver, "HTTP/1.0" ) && strcmp ( http_ver, "HTTP/1.1" ))
|
||||||
{
|
{
|
||||||
|
@ -332,14 +379,62 @@ __AI_webservlet_thread ( void *arg )
|
||||||
if ( !strcasecmp ( extension, "html" ))
|
if ( !strcasecmp ( extension, "html" ))
|
||||||
{
|
{
|
||||||
strncpy ( content_type, "text/html", sizeof ( content_type ));
|
strncpy ( content_type, "text/html", sizeof ( content_type ));
|
||||||
} else if ( !strcasecmp ( extension, "css" ))
|
} else if ( !strcasecmp ( extension, "css" )) {
|
||||||
{
|
|
||||||
strncpy ( content_type, "text/css", sizeof ( content_type ));
|
strncpy ( content_type, "text/css", sizeof ( content_type ));
|
||||||
} else if ( !strcasecmp ( extension, "js" ))
|
} else if ( !strcasecmp ( extension, "js" )) {
|
||||||
{
|
|
||||||
strncpy ( content_type, "application/x-javascript", sizeof ( content_type ));
|
strncpy ( content_type, "application/x-javascript", sizeof ( content_type ));
|
||||||
|
} else if ( !strcasecmp ( extension, "json" )) {
|
||||||
|
strncpy ( content_type, "application/json", sizeof ( content_type ));
|
||||||
} else if ( !strcasecmp ( extension, "jpg" ) || !strcasecmp ( extension, "jpeg" )) {
|
} else if ( !strcasecmp ( extension, "jpg" ) || !strcasecmp ( extension, "jpeg" )) {
|
||||||
strncpy ( content_type, "image/jpeg", sizeof ( content_type ));
|
strncpy ( content_type, "image/jpeg", sizeof ( content_type ));
|
||||||
|
} else if ( !strcasecmp ( extension, "cgi" )) {
|
||||||
|
/* If it's not executable, it's not a CGI */
|
||||||
|
if ( !( st.st_mode & S_IXOTH ))
|
||||||
|
strncpy ( content_type, "text/plain", sizeof ( content_type ));
|
||||||
|
else {
|
||||||
|
is_cgi = true;
|
||||||
|
http_response = NULL;
|
||||||
|
http_response_len = 1;
|
||||||
|
|
||||||
|
if ( !( cgi_cmd = (char*) alloca ( strlen ( req_file_absolute_path ) + 20 )))
|
||||||
|
{
|
||||||
|
pthread_exit ((void*) 0);
|
||||||
|
return (void*) 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
sprintf ( cgi_cmd, "/bin/sh -c %s", req_file_absolute_path );
|
||||||
|
|
||||||
|
if ( !( pipe = popen ( cgi_cmd, "r" )))
|
||||||
|
{
|
||||||
|
pthread_exit ((void*) 0);
|
||||||
|
return (void*) 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
while ( fread ( &ch, 1, 1, pipe ) > 0 )
|
||||||
|
{
|
||||||
|
if ( !( http_response = (char*) realloc ( http_response, ++http_response_len )))
|
||||||
|
{
|
||||||
|
pthread_exit ((void*) 0);
|
||||||
|
return (void*) 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
http_response [ http_response_len - 2 ] = ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
http_response [ http_response_len - 1 ] = 0;
|
||||||
|
pclose ( pipe );
|
||||||
|
|
||||||
|
if ( !http_response )
|
||||||
|
{
|
||||||
|
if ( !( http_response = (char*) malloc ( 2 )))
|
||||||
|
{
|
||||||
|
pthread_exit ((void*) 0);
|
||||||
|
return (void*) 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
http_response[0] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
} else if ( !strcasecmp ( extension, "gif" ) || !strcasecmp ( extension, "png" ) ||
|
} else if ( !strcasecmp ( extension, "gif" ) || !strcasecmp ( extension, "png" ) ||
|
||||||
!strcasecmp ( extension, "bmp" ) || !strcasecmp ( extension, "tif" ) ||
|
!strcasecmp ( extension, "bmp" ) || !strcasecmp ( extension, "tif" ) ||
|
||||||
!strcasecmp ( extension, "ppm" )) {
|
!strcasecmp ( extension, "ppm" )) {
|
||||||
|
@ -349,42 +444,144 @@ __AI_webservlet_thread ( void *arg )
|
||||||
strncpy ( content_type, "text/plain", sizeof ( content_type ));
|
strncpy ( content_type, "text/plain", sizeof ( content_type ));
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( !( http_response = (char*) alloca ( st.st_size + 2 )))
|
if ( !is_cgi )
|
||||||
{
|
{
|
||||||
pthread_exit ((void*) 0);
|
if ( !( http_response = (char*) alloca ( st.st_size + 2 )))
|
||||||
return (void*) 0;
|
{
|
||||||
|
pthread_exit ((void*) 0);
|
||||||
|
return (void*) 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
memset ( http_response, 0, st.st_size + 2 );
|
||||||
|
fread ( http_response, st.st_size, 1, fp );
|
||||||
|
fclose ( fp );
|
||||||
}
|
}
|
||||||
|
|
||||||
memset ( http_response, 0, st.st_size + 2 );
|
|
||||||
fread ( http_response, st.st_size, 1, fp );
|
|
||||||
fclose ( fp );
|
|
||||||
|
|
||||||
ltime = time ( NULL );
|
ltime = time ( NULL );
|
||||||
strtime = strdup ( ctime ( <ime ));
|
strtime = strdup ( ctime ( <ime ));
|
||||||
strtime [ strlen(strtime) - 1 ] = 0;
|
strtime [ strlen(strtime) - 1 ] = 0;
|
||||||
snprintf ( http_headers, max_headers_length, HTTP_RESPONSE_HEADERS_FORMAT,
|
|
||||||
http_ver, 200, "Found", strtime, config->webserv_banner,
|
if ( is_cgi )
|
||||||
content_type, strlen ( http_response ));
|
{
|
||||||
|
snprintf ( http_headers, max_headers_length, HTTP_CGI_RESPONSE_HEADERS_FORMAT,
|
||||||
|
http_ver, 200, "Found", strtime, config->webserv_banner, strlen ( http_response ));
|
||||||
|
} else {
|
||||||
|
snprintf ( http_headers, max_headers_length, HTTP_RESPONSE_HEADERS_FORMAT,
|
||||||
|
http_ver, 200, "Found", strtime, config->webserv_banner,
|
||||||
|
content_type, strlen ( http_response ));
|
||||||
|
}
|
||||||
|
|
||||||
free ( strtime );
|
free ( strtime );
|
||||||
free ( line );
|
free ( line );
|
||||||
line = NULL;
|
line = NULL;
|
||||||
continue;
|
continue;
|
||||||
} else if ( nlines == 0 ) {
|
} else {
|
||||||
snprintf ( http_response, max_content_length, HTTP_ERR_RESPONSE_FORMAT,
|
if ( nlines == 0 )
|
||||||
405, "Method Not Allowed", "Method Not Allowed",
|
{
|
||||||
"The requested HTTP method is not allowed",
|
snprintf ( http_response, max_content_length, HTTP_ERR_RESPONSE_FORMAT,
|
||||||
config->webserv_banner );
|
405, "Method Not Allowed", "Method Not Allowed",
|
||||||
|
"The requested HTTP method is not allowed",
|
||||||
|
config->webserv_banner );
|
||||||
|
|
||||||
ltime = time ( NULL );
|
ltime = time ( NULL );
|
||||||
strtime = strdup ( ctime ( <ime ));
|
strtime = strdup ( ctime ( <ime ));
|
||||||
strtime [ strlen(strtime) - 1 ] = 0;
|
strtime [ strlen(strtime) - 1 ] = 0;
|
||||||
snprintf ( http_headers, max_headers_length, HTTP_RESPONSE_HEADERS_FORMAT,
|
snprintf ( http_headers, max_headers_length, HTTP_RESPONSE_HEADERS_FORMAT,
|
||||||
"HTTP/1.1", 405, "Method Not Allowed", strtime, "text/html",
|
"HTTP/1.1", 405, "Method Not Allowed", strtime, "text/html",
|
||||||
config->webserv_banner, strlen ( http_response ));
|
config->webserv_banner, strlen ( http_response ));
|
||||||
free ( strtime );
|
free ( strtime );
|
||||||
free ( line );
|
free ( line );
|
||||||
line = NULL;
|
line = NULL;
|
||||||
continue;
|
continue;
|
||||||
|
} else if ( preg_match ( "\\s*Content-Length\\s*:\\s*([0-9]+)", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "CONTENT_LENGTH", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
} else if ( preg_match ( "\\s*Content-Type\\s*:\\s*(.+?)\r?\n?$", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "CONTENT_TYPE", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
} else if ( preg_match ( "\\s*Accept\\s*:\\s*(.+?)\r?\n?$", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "HTTP_ACCEPT", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
} else if ( preg_match ( "\\s*Accept-Charset\\s*:\\s*(.+?)\r?\n?$", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "HTTP_ACCEPT_CHARSET", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
} else if ( preg_match ( "\\s*Accept-Encoding\\s*:\\s*(.+?)\r?\n?$", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "HTTP_ACCEPT_ENCODING", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
} else if ( preg_match ( "\\s*Accept-Language\\s*:\\s*(.+?)\r?\n?$", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "HTTP_ACCEPT_LANGUAGE", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
} else if ( preg_match ( "\\s*Connection\\s*:\\s*(.+?)\r?\n?$", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "HTTP_CONNECTION", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
} else if ( preg_match ( "\\s*Cookie\\s*:\\s*(.+?)\r?\n?$", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "HTTP_COOKIE", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
} else if ( preg_match ( "\\s*Reason\\s*:\\s*(.+?)\r?\n?$", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "HTTP_REASON", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
} else if ( preg_match ( "\\s*User-Agent\\s*:\\s*(.+?)\r?\n?$", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "HTTP_USER_AGENT", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
} else if ( preg_match ( "\\s*Referrer\\s*:\\s*(.+?)\r?\n?$", line, &matches, &nmatches ) > 0 ) {
|
||||||
|
setenv ( "HTTP_REFERRER", matches[0], 1 );
|
||||||
|
|
||||||
|
for ( i=0; i < nmatches; i++ )
|
||||||
|
free ( matches[i] );
|
||||||
|
|
||||||
|
free ( matches );
|
||||||
|
matches = NULL;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
free ( line );
|
free ( line );
|
||||||
|
@ -393,8 +590,17 @@ __AI_webservlet_thread ( void *arg )
|
||||||
|
|
||||||
fprintf ( sock, "%s%s", http_headers, http_response );
|
fprintf ( sock, "%s%s", http_headers, http_response );
|
||||||
fclose ( sock );
|
fclose ( sock );
|
||||||
close ( *sd );
|
close ( sd );
|
||||||
|
free ( arg );
|
||||||
|
|
||||||
|
if ( query_string )
|
||||||
|
free ( query_string );
|
||||||
|
|
||||||
|
if ( is_cgi )
|
||||||
|
free ( http_response );
|
||||||
|
|
||||||
pthread_exit ( 0 );
|
pthread_exit ( 0 );
|
||||||
|
return (void*) 0;
|
||||||
} /* ----- end of function __AI_webservlet_thread ----- */
|
} /* ----- end of function __AI_webservlet_thread ----- */
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -406,11 +612,12 @@ AI_webserv_thread ( void *arg )
|
||||||
{
|
{
|
||||||
int on = 1,
|
int on = 1,
|
||||||
sd,
|
sd,
|
||||||
client_sd;
|
sockaddr_size;
|
||||||
|
|
||||||
struct sockaddr_in addr;
|
struct sockaddr_in addr;
|
||||||
pthread_t servlet_thread;
|
pthread_t servlet_thread;
|
||||||
pthread_attr_t attr;
|
pthread_attr_t attr;
|
||||||
|
conn_info *conn;
|
||||||
|
|
||||||
if (( sd = socket ( AF_INET, SOCK_STREAM, 0 )) < 0 )
|
if (( sd = socket ( AF_INET, SOCK_STREAM, 0 )) < 0 )
|
||||||
{
|
{
|
||||||
|
@ -432,7 +639,7 @@ AI_webserv_thread ( void *arg )
|
||||||
AI_fatal_err ( "Error while binding socket", __FILE__, __LINE__ );
|
AI_fatal_err ( "Error while binding socket", __FILE__, __LINE__ );
|
||||||
}
|
}
|
||||||
|
|
||||||
if ( listen ( sd, 10 ) < 0 )
|
if ( listen ( sd, 100 ) < 0 )
|
||||||
{
|
{
|
||||||
AI_fatal_err ( "Error while setting the socket in listen mode", __FILE__, __LINE__ );
|
AI_fatal_err ( "Error while setting the socket in listen mode", __FILE__, __LINE__ );
|
||||||
}
|
}
|
||||||
|
@ -442,10 +649,15 @@ AI_webserv_thread ( void *arg )
|
||||||
|
|
||||||
while ( 1 )
|
while ( 1 )
|
||||||
{
|
{
|
||||||
if (( client_sd = accept ( sd, NULL, NULL )) < 0 )
|
if ( !( conn = (conn_info*) malloc ( sizeof ( conn_info ))))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
if ( pthread_create ( &servlet_thread, &attr, __AI_webservlet_thread, (void*) &client_sd ) != 0 )
|
memset ( conn, 0, sizeof ( conn ));
|
||||||
|
|
||||||
|
if (( conn->sd = accept ( sd, (struct sockaddr*) &(conn->client), (socklen_t*) &sockaddr_size )) < 0 )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if ( pthread_create ( &servlet_thread, &attr, __AI_webservlet_thread, (void*) conn ) != 0 )
|
||||||
{
|
{
|
||||||
AI_fatal_err ( "Error while creating the webservlet thread", __FILE__, __LINE__ );
|
AI_fatal_err ( "Error while creating the webservlet thread", __FILE__, __LINE__ );
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue