Project

General

Profile

Download (15.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
	graph.php
4
*/
5
/* ====================================================================
6
 *  Copyright (c)  2004-2015  Electric Sheep Fencing, LLC. All rights reserved.
7
 *  Copyright (c)  2004-2006 T. Lechat <dev@lechat.org>, Manuel Kasper <mk@neon1.net>
8
 *							 and Jonathan Watt <jwatt@jwatt.org>
9
 *
10
 *  Some or all of this file is based on the m0n0wall project which is
11
 *  Copyright (c)  2004 Manuel Kasper (BSD 2 clause)
12
 *
13
 *  Redistribution and use in source and binary forms, with or without modification,
14
 *  are permitted provided that the following conditions are met:
15
 *
16
 *  1. Redistributions of source code must retain the above copyright notice,
17
 *      this list of conditions and the following disclaimer.
18
 *
19
 *  2. Redistributions in binary form must reproduce the above copyright
20
 *      notice, this list of conditions and the following disclaimer in
21
 *      the documentation and/or other materials provided with the
22
 *      distribution.
23
 *
24
 *  3. All advertising materials mentioning features or use of this software
25
 *      must display the following acknowledgment:
26
 *      "This product includes software developed by the pfSense Project
27
 *       for use in the pfSense software distribution. (http://www.pfsense.org/).
28
 *
29
 *  4. The names "pfSense" and "pfSense Project" must not be used to
30
 *       endorse or promote products derived from this software without
31
 *       prior written permission. For written permission, please contact
32
 *       coreteam@pfsense.org.
33
 *
34
 *  5. Products derived from this software may not be called "pfSense"
35
 *      nor may "pfSense" appear in their names without prior written
36
 *      permission of the Electric Sheep Fencing, LLC.
37
 *
38
 *  6. Redistributions of any form whatsoever must retain the following
39
 *      acknowledgment:
40
 *
41
 *  "This product includes software developed by the pfSense Project
42
 *  for use in the pfSense software distribution (http://www.pfsense.org/).
43
 *
44
 *  THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
45
 *  EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
47
 *  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
48
 *  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
49
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
50
 *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
51
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52
 *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
53
 *  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
54
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
55
 *  OF THE POSSIBILITY OF SUCH DAMAGE.
56
 *
57
 *  ====================================================================
58
 *
59
 */
60

    
61
##|+PRIV
62
##|*IDENT=page-diagnostics-interfacetraffic
63
##|*NAME=Diagnostics: Interface Traffic
64
##|*DESCR=Allow access to the 'Diagnostics: Interface Traffic' page.
65
##|*MATCH=graph.php*
66
##|-PRIV
67

    
68
require("globals.inc");
69
require("guiconfig.inc");
70

    
71
header("Last-Modified: " . gmdate("D, j M Y H:i:s") . " GMT");
72
header("Expires: " . gmdate("D, j M Y H:i:s", time()) . " GMT");
73
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP/1.1
74
header("Pragma: no-cache"); // HTTP/1.0
75
header("Content-type: image/svg+xml");
76

    
77
/********** HTTP GET Based Conf ***********/
78
$ifnum = @$_GET["ifnum"];  // BSD / SNMP interface name / number
79
$ifnum = get_real_interface($ifnum);
80
$ifname = @$_GET["ifname"]?$_GET["ifname"]:"Interface $ifnum";  //Interface name that will be showed on top right of graph
81

    
82
/********* Other conf *******/
83
if (isset($config["widgets"]["trafficgraphs"]["scale_type"])) {
84
	$scale_type = $config["widgets"]["trafficgraphs"]["scale_type"];
85
} else {
86
	$scale_type = "up";
87
}
88

    
89
$nb_plot=120;                   //NB plot in graph
90
if ($_GET["timeint"]) {
91
	$time_interval = $_GET["timeint"];		//Refresh time Interval
92
} else {
93
	$time_interval = 3;
94
}
95

    
96
if ($_GET["initdelay"]) {
97
	$init_delay = $_GET["initdelay"];		//Initial Delay
98
} else {
99
	$init_delay = 3;
100
}
101

    
102
//SVG attributes
103
$attribs['axis']='fill="black" stroke="black"';
104
$attribs['in']='fill="#FF0000" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="7"';
105
$attribs['out']='fill="#000000" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="7"';
106
$attribs['graph_in']='fill="none" stroke="#FF0000" stroke-opacity="0.8"';
107
$attribs['graph_out']='fill="none" stroke="#000000" stroke-opacity="0.8"';
108
$attribs['legend']='fill="black" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4"';
109
$attribs['graphname']='fill="#FF0000" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="8"';
110
$attribs['grid_txt']='fill="gray" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="6"';
111
$attribs['grid']='stroke="gray" stroke-opacity="0.5"';
112
$attribs['switch_unit']='fill="#FF0000" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4" text-decoration="underline"';
113
$attribs['switch_scale']='fill="#FF0000" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4" text-decoration="underline"';
114
$attribs['error']='fill="blue" font-family="Arial" font-size="4"';
115
$attribs['collect_initial']='fill="gray" font-family="Tahoma, Verdana, Arial, Helvetica, sans-serif" font-size="4"';
116

    
117
//Error text if we cannot fetch data : depends on which method is used
118
$error_text = "Cannot get data about interface " . htmlspecialchars($ifnum);
119

    
120
$height=100;            //SVG internal height : do not modify
121
$width=200;             //SVG internal width : do not modify
122

    
123
$fetch_link = "ifstats.php?if=" . htmlspecialchars($ifnum);
124

    
125
/********* Graph DATA **************/
126
print('<?xml version="1.0" encoding="UTF-8"?>' . "\n");?>
127
<svg width="100%" height="100%" viewBox="0 0 <?=$width?> <?=$height?>" preserveAspectRatio="none" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="init(evt)">
128
	<g id="graph">
129
		<rect id="bg" x1="0" y1="0" width="100%" height="100%" fill="white"/>
130
		<line id="axis_x" x1="0" y1="0" x2="0" y2="100%" <?=$attribs['axis']?>/>
131
		<line id="axis_y" x1="0" y1="100%" x2="100%" y2="100%" <?=$attribs['axis']?>/>
132
		<path id="graph_out" d="M0 <?=$height?> L 0 <?=$height?>" <?=$attribs['graph_out']?>/>
133
		<path id="graph_in" d="M0 <?=$height?> L 0 <?=$height?>" <?=$attribs['graph_in']?>/>
134
		<path id="grid" d="M0 <?=$height/4*1?> L <?=$width?> <?=$height/4*1?> M0 <?=$height/4*2?> L <?=$width?> <?=$height/4*2?> M0 <?=$height/4*3?> L <?=$width?> <?=$height/4*3?>" <?=$attribs['grid']?>/>
135
		<text id="grid_txt1" x="<?=$width?>" y="<?=$height/4*1?>" <?=$attribs['grid_txt']?> text-anchor="end"> </text>
136
		<text id="grid_txt2" x="<?=$width?>" y="<?=$height/4*2?>" <?=$attribs['grid_txt']?> text-anchor="end"> </text>
137
		<text id="grid_txt3" x="<?=$width?>" y="<?=$height/4*3?>" <?=$attribs['grid_txt']?> text-anchor="end"> </text>
138
		<text id="graph_in_lbl" x="5" y="8" <?=$attribs['in']?>><?=gettext("In"); ?></text>
139
		<text id="graph_out_lbl" x="5" y="16" <?=$attribs['out']?>><?=gettext("Out"); ?></text>
140
		<text id="graph_in_txt" x="20" y="8" <?=$attribs['in']?>> </text>
141
		<text id="graph_out_txt" x="20" y="16" <?=$attribs['out']?>> </text>
142
		<text id="ifname" x="<?=$width?>" y="8" <?=$attribs['graphname']?> text-anchor="end"><?=htmlspecialchars($ifname)?></text>
143
		<text id="switch_unit" x="<?=$width*0.55?>" y="5" <?=$attribs['switch_unit']?>><?=gettext("Switch to bytes/s"); ?></text>
144
		<text id="switch_scale" x="<?=$width*0.55?>" y="11" <?=$attribs['switch_scale']?>><?=gettext("AutoScale"); ?> (<?=$scale_type?>)</text>
145
		<text id="date" x="<?=$width*0.33?>" y="5" <?=$attribs['legend']?>> </text>
146
		<text id="time" x="<?=$width*0.33?>" y="11" <?=$attribs['legend']?>> </text>
147
		<text id="graphlast" x="<?=$width*0.55?>" y="17" <?=$attribs['legend']?>><?=gettext("Graph shows last"); ?> <?=$time_interval*$nb_plot?> <?=gettext("seconds"); ?></text>
148
		<polygon id="axis_arrow_x" <?=$attribs['axis']?> points="<?=($width) . "," . ($height)?> <?=($width-2) . "," . ($height-2)?> <?=($width-2) . "," . $height?>"/>
149
		<text id="error" x="<?=$width*0.5?>" y="<?=$height*0.5?>" visibility="hidden" <?=$attribs['error']?> text-anchor="middle"><?=$error_text?></text>
150
		<text id="collect_initial" x="<?=$width*0.5?>" y="<?=$height*0.5?>" visibility="hidden" <?=$attribs['collect_initial']?> text-anchor="middle"><?=gettext("Collecting initial data, please wait"); ?>...</text>
151
	</g>
152
	<script type="text/ecmascript">
153
	<![CDATA[
154

    
155
/**
156
 * getURL is a proprietary Adobe function, but it's simplicity has made it very
157
 * popular. If getURL is undefined we spin our own by wrapping XMLHttpRequest.
158
 */
159
if (typeof getURL == 'undefined') {
160
	getURL = function(url, callback) {
161
		if (!url) {
162
			throw '<?=gettext("No URL for getURL"); ?>';
163
		}
164

    
165
		try {
166
			if (typeof callback.operationComplete == 'function') {
167
				callback = callback.operationComplete;
168
			}
169
		} catch (e) {}
170
		if (typeof callback != 'function') {
171
			throw '<?=gettext("No callback function for getURL"); ?>';
172
		}
173

    
174
		var http_request = null;
175
		if (typeof XMLHttpRequest != 'undefined') {
176
			http_request = new XMLHttpRequest();
177
		} else if (typeof ActiveXObject != 'undefined') {
178
			try {
179
				http_request = new ActiveXObject('Msxml2.XMLHTTP');
180
			} catch (e) {
181
				try {
182
				http_request = new ActiveXObject('Microsoft.XMLHTTP');
183
				} catch (e) {}
184
			}
185
		}
186
		if (!http_request) {
187
			throw '<?=gettext("Both getURL and XMLHttpRequest are undefined"); ?>';
188
		}
189

    
190
		http_request.onreadystatechange = function() {
191
			if (http_request.readyState == 4) {
192
				callback( { success : true,
193
					content : http_request.responseText,
194
					contentType : http_request.getResponseHeader("Content-Type") } );
195
			}
196
		}
197
		http_request.open('GET', url, true);
198
		http_request.send(null);
199
	}
200
}
201

    
202
var SVGDoc = null;
203
var last_ifin = 0;
204
var last_ifout = 0;
205
var last_ugmt = 0;
206
var max = 0;
207
var plot_in = new Array();
208
var plot_out = new Array();
209

    
210
var max_num_points = <?=$nb_plot?>;  // maximum number of plot data points
211
var step = <?=$width?> / max_num_points ;
212
var unit = 'bits';
213
var scale_type = '<?=$scale_type?>';
214

    
215
function init(evt) {
216
	SVGDoc = evt.target.ownerDocument;
217
	SVGDoc.getElementById("switch_unit").addEventListener("mousedown", switch_unit, false);
218
	SVGDoc.getElementById("switch_scale").addEventListener("mousedown", switch_scale, false);
219

    
220
	fetch_data();
221
}
222

    
223
function switch_unit(event) {
224
	SVGDoc.getElementById('switch_unit').firstChild.data = '<?=gettext("Switch to"); ?> ' + unit + '/s';
225
	unit = (unit == 'bits') ? 'bytes' : 'bits';
226
}
227

    
228
function switch_scale(event) {
229
	scale_type = (scale_type == 'up') ? '<?=gettext("follow"); ?>' : '<?=gettext("up"); ?>';
230
	SVGDoc.getElementById('switch_scale').firstChild.data = 'AutoScale (' + scale_type + ')';
231
}
232

    
233
function fetch_data() {
234
	getURL('<?=$fetch_link?>', plot_data);
235
}
236

    
237
function plot_data(obj) {
238
	// Show datetimelegend
239
	var now = new Date();
240
	var time = LZ(now.getHours()) + ":" + LZ(now.getMinutes()) + ":" + LZ(now.getSeconds());
241
	SVGDoc.getElementById('time').firstChild.data = time;
242
	var date = (now.getMonth()+1) + "/" + now.getDate() + "/" + now.getFullYear();
243
	SVGDoc.getElementById('date').firstChild.data = date;
244

    
245
	if (!obj.success) {
246
		return handle_error();  // getURL failed to get data
247
	}
248

    
249
	var t = obj.content.split("|");
250
	var ugmt = parseFloat(t[0]);  // ugmt is an unixtimestamp style
251
	var ifin = parseInt(t[1], 10);    // number of bytes received by the interface
252
	var ifout = parseInt(t[2], 10);   // number of bytes sent by the interface
253
	var scale;
254

    
255
	if (!isNumber(ifin) || !isNumber(ifout)) {
256
		return handle_error();
257
	}
258

    
259
	var diff_ugmt  = ugmt - last_ugmt;
260
	var diff_ifin  = ifin - last_ifin;
261
	var diff_ifout = ifout - last_ifout;
262

    
263
	if (diff_ugmt == 0) {
264
		diff_ugmt = 1;  /* avoid division by zero */
265
	}
266

    
267
	last_ugmt = ugmt;
268
	last_ifin = ifin;
269
	last_ifout = ifout;
270
	var graphTimerId = 0;
271
	switch (plot_in.length) {
272
		case 0:
273
			SVGDoc.getElementById("collect_initial").setAttributeNS(null, 'visibility', 'visible');
274
			plot_in[0] = diff_ifin / diff_ugmt;
275
			plot_out[0] = diff_ifout / diff_ugmt;
276
			setTimeout('fetch_data()', <?=1000*($time_interval + $init_delay)?>);
277
			return;
278
		case 1:
279
			SVGDoc.getElementById("collect_initial").setAttributeNS(null, 'visibility', 'hidden');
280
			break;
281
		case max_num_points:
282
			// shift plot to left if the maximum number of plot points has been reached
283
			var i = 0;
284
			while (i < max_num_points) {
285
				plot_in[i] = plot_in[i+1];
286
				plot_out[i] = plot_out[++i];
287
			}
288
			plot_in.length--;
289
			plot_out.length--;
290
	}
291

    
292
	plot_in[plot_in.length] = diff_ifin / diff_ugmt;
293
	plot_out[plot_out.length]= diff_ifout / diff_ugmt;
294
	var index_plot = plot_in.length - 1;
295

    
296
	SVGDoc.getElementById('graph_in_txt').firstChild.data = formatSpeed(plot_in[index_plot], unit);
297
	SVGDoc.getElementById('graph_out_txt').firstChild.data = formatSpeed(plot_out[index_plot], unit);
298

    
299
	/* determine peak for sensible scaling */
300
	if (scale_type == 'up') {
301
		if (plot_in[index_plot] > max) {
302
			max = plot_in[index_plot];
303
		}
304
		if (plot_out[index_plot] > max) {
305
			max = plot_out[index_plot];
306
		}
307
	} else if (scale_type == 'follow') {
308
		i = 0;
309
		max = 0;
310
		while (i < plot_in.length) {
311
			if (plot_in[i] > max) {
312
				max = plot_in[i];
313
			}
314
			if (plot_out[i] > max) {
315
				max = plot_out[i];
316
			}
317
			i++;
318
		}
319
	}
320

    
321
	var rmax;  // max, rounded up
322

    
323
	if (unit == 'bits') {
324
		/* round up max, such that
325
		   100 kbps -> 200 kbps -> 400 kbps -> 800 kbps -> 1 Mbps -> 2 Mbps -> ... */
326
		rmax = 12500;
327
		i = 0;
328
		while (max > rmax) {
329
			i++;
330
			if (i && (i % 4 == 0)) {
331
				rmax *= 1.25;
332
			} else {
333
				rmax *= 2;
334
			}
335
		}
336
	} else {
337
		/* round up max, such that
338
		   10 KB/s -> 20 KB/s -> 40 KB/s -> 80 KB/s -> 100 KB/s -> 200 KB/s -> 400 KB/s -> 800 KB/s -> 1 MB/s ... */
339
		rmax = 10240;
340
		i = 0;
341
		while (max > rmax) {
342
			i++;
343
			if (i && (i % 4 == 0)) {
344
				rmax *= 1.25;
345
			} else {
346
				rmax *= 2;
347
			}
348

    
349
			if (i == 8) {
350
				rmax *= 1.024;
351
			}
352
		}
353
	}
354

    
355
	scale = <?=$height?> / rmax;
356

    
357
	/* change labels accordingly */
358
	SVGDoc.getElementById('grid_txt1').firstChild.data = formatSpeed(3*rmax/4, unit);
359
	SVGDoc.getElementById('grid_txt2').firstChild.data = formatSpeed(2*rmax/4, unit);
360
	SVGDoc.getElementById('grid_txt3').firstChild.data = formatSpeed(rmax/4, unit);
361

    
362
	var path_in = "M 0 " + (<?=$height?> - (plot_in[0] * scale));
363
	var path_out = "M 0 " + (<?=$height?> - (plot_out[0] * scale));
364
	for (i = 1; i < plot_in.length; i++) {
365
		var x = step * i;
366
		var y_in = <?=$height?> - (plot_in[i] * scale);
367
		var y_out = <?=$height?> - (plot_out[i] * scale);
368
		path_in += " L" + x + " " + y_in;
369
		path_out += " L" + x + " " + y_out;
370
	}
371

    
372
	SVGDoc.getElementById('error').setAttributeNS(null, 'visibility', 'hidden');
373
	SVGDoc.getElementById('graph_in').setAttributeNS(null, 'd', path_in);
374
	SVGDoc.getElementById('graph_out').setAttributeNS(null, 'd', path_out);
375

    
376
	setTimeout('fetch_data()', <?=1000*$time_interval?>);
377
}
378

    
379
function handle_error() {
380
	SVGDoc.getElementById("error").setAttributeNS(null, 'visibility', 'visible');
381
	setTimeout('fetch_data()', <?=1000*$time_interval?>);
382
}
383

    
384
function isNumber(a) {
385
	return typeof a == 'number' && isFinite(a);
386
}
387

    
388
function formatSpeed(speed, unit) {
389
	if (unit == 'bits') {
390
		return formatSpeedBits(speed);
391
	}
392
	if (unit == 'bytes') {
393
		return formatSpeedBytes(speed);
394
	}
395
}
396

    
397
function formatSpeedBits(speed) {
398
	// format speed in bits/sec, input: bytes/sec
399
	if (speed < 125000) {
400
		return Math.round(speed / 125) + " <?=gettext("Kbps"); ?>";
401
	}
402
	if (speed < 125000000) {
403
		return Math.round(speed / 1250)/100 + " <?=gettext("Mbps"); ?>";
404
	}
405
	// else
406
	return Math.round(speed / 1250000)/100 + " <?=gettext("Gbps"); ?>";  /* wow! */
407
}
408

    
409
function formatSpeedBytes(speed) {
410
	// format speed in bytes/sec, input:  bytes/sec
411
	if (speed < 1048576) {
412
		return Math.round(speed / 10.24)/100 + " <?=gettext("KB/s"); ?>";
413
	}
414
	if (speed < 1073741824) {
415
		return Math.round(speed / 10485.76)/100 + " <?=gettext("MB/s"); ?>";
416
	}
417
	// else
418
	return Math.round(speed / 10737418.24)/100 + " <?=gettext("GB/s"); ?>";  /* wow! */
419
}
420

    
421
function LZ(x) {
422
	return (x < 0 || x > 9 ? "" : "0") + x;
423
}
424

    
425
    ]]>
426
	</script>
427
</svg>
(62-62/229)