Flash ActionScript 3 API for Mikrotik RouterOS 3.x
Lately I have been familiar with the RouterOS series, when we got us a RouterBoard 493. At first I was a bit sceptical since I had never heard of RouterOS or Mikrotik. But as soon as I started testing this nice little hardware/software out, I found out that this was one exceptional nice software. And the nice hardware solutions is also nice. You can buy barebone RouterBoards without casing, and put them inside what you want, or buy a RouterOS license and build your own x86 router with standard x86 hardware.
The great thing about these routers is that they are so configurable, and easy to administer. You should all try them out yourself. They are extremely cheap, and extremely full of features. I know a lot of ISP’s around the world use only mikrotik equiptment in their wireless networks. Since they are very easy to set up with several wireless cards, and they have exceptionally good drivers, where you can fine tune all the parameters.
Anywyas, in addition to supporting configuration over Telnet/SSH/MAC-telnet. They also have a so called RouterOS API. This is a nice little API that gives you computer-friendly access to all the features in the configuration of the box.
Via the API you can read info, set configuration (live), and even listen for events. For example, list out the dBm to all connected WLAN users. Or get notified when someoen pulls a network cable. etc.
The API is “open documentation” and you are welcome to create libraries to different languages and post on their site. They already have PHP, Ruby, Perl, Java, etc implementations, but I wanted to be able to create a Flash AIR application to display and configure routers. So I created a Flash ActionScript 3 class for it.
Now I can create nice interfaces displaying live info from the router, and simple(or andvanced) configuration of the device.
The ActionScript classes looks like this:
// ApiSocket.as
//
// RouterOS API class
// Author: Håkon Nessjøen
// Date: 2. May 2009
//
package {
import flash.errors.*;
import flash.events.*;
import flash.utils.ByteArray;
import com.adobe.crypto.MD5;
import flash.net.Socket;
public class ApiSocket extends Socket {
static public var RECEIVED:String = "received";
static public var LOGIN:String = "loggedin";
private var cmd:String;
private var doLogin:int;
private var user:String;
private var password:String;
private var returnData:Array;
private var returnPos:int;
private var toread:int;
private var firstRe:int;
private var tag:String;
private var gotDone:Boolean;
private var gotTrap:Boolean;
private var gotFatal:Boolean;
public function ApiSocket(host:String, port:uint) {
super(host, port);
toread = 0;
doLogin = 0;
addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
}
public function login(u:String, p:String) {
doLogin = 1;
user = u;
password = p;
sendRequest("/login");
}
public function sendRequest(... outData):void {
returnData = new Array();
returnPos = 0;
firstRe = 0;
gotDone = false;
gotTrap = false;
gotFatal = false;
tag = "";
cmd = outData[0];
returnData[returnPos] = new Object();
for (var i:int = 0; i < outData.length; ++i) {
var data:ByteArray = new ByteArray();
var len:uint = outData[i].length;
if (len < 0x80)
data.writeByte(len);
else
if (len < 0x4000) {
len |= 0x8000;
data.writeByte((len >> 8) & 0xff);
data.writeByte(len & 0xff);
} else
if (len < 0x200000) {
len |= 0xC00000;
data.writeByte((len >> 16) & 0xff);
data.writeByte((len >> 8) & 0xff);
data.writeByte(len & 0xff);
} else
if (len < 0x10000000) {
len |= 0xE0000000;
data.writeByte((len >> 24) & 0xff);
data.writeByte((len >> 16) & 0xff);
data.writeByte((len >> 8) & 0xff);
data.writeByte(len & 0xff);
} else {
data.writeByte(0xF0);
data.writeByte((len >> 24) & 0xff);
data.writeByte((len >> 16) & 0xff);
data.writeByte((len >> 8) & 0xff);
data.writeByte(len & 0xff);
}
writeBytes(data);
writeUTFBytes(outData[i]);
}
writeByte(0);
flush();
}
private function readResponse():void {
var len:int;
if (toread == 0) {
var len1:uint = readUnsignedByte();
if (len1 == 0) {
if (gotDone || gotTrap || gotFatal) {
if (doLogin == 1) {
if (returnData[0].ret) {
var chal:ByteArray = new ByteArray();
var md5:ByteArray = new ByteArray();
for (var i:int = 0; i < returnData[0].ret.length; i += 2) {
chal.writeByte(int("0x" + returnData[0].ret.substr(i,2)));
}
md5.writeByte(0);
md5.writeUTFBytes(password);
md5.writeBytes(chal);
doLogin++;
// Send challenge response
sendRequest("/login", "=name=" + user, "=response=00" + MD5.hashBytes(md5));
}
} else if (doLogin == 2) {
doLogin = 0;
dispatchEvent(new ApiEvent(ApiSocket.LOGIN, "", returnData, gotDone ? 'done' : (gotFatal ? 'fatal' : 'trap')));
} else {
dispatchEvent(new ApiEvent(ApiSocket.RECEIVED, tag, returnData, gotDone ? 'done' : (gotFatal ? 'fatal' : 'trap')));
}
}
if (bytesAvailable)
readResponse();
else
return;
}
if (len1 >= 0xF0) {
len = readUnsignedByte();
len = (len << 8) + readUnsignedByte();
len = (len << 8) + readUnsignedByte();
len = (len << 8) + readUnsignedByte();
} else
if (len1 >= 0xE0) {
len = ((len1 & 15) << 8) + readUnsignedByte();
len = (len << 8) + readUnsignedByte();
len = (len << 8) + readUnsignedByte();
} else
if (len1 >= 0xC0) {
len = ((len1 & 31) << 8) + readUnsignedByte();
len = (len << 8) + readUnsignedByte();
} else
if (len1 >= 0x80) {
len = ((len1 & 63) << 8) + readUnsignedByte();
} else
len = len1;
toread = len;
}
// Calculate how much data of the full length that is available right now
var slen:int = bytesAvailable > toread ? toread : bytesAvailable;
// Calculate how much data that has to be read later
toread = toread > bytesAvailable ? toread - bytesAvailable : 0;
// Read relevant data
var str:String = readUTFBytes(slen);
if (toread == 0) {
if (str == '!re') {
firstRe++;
if (firstRe > 1) {
returnPos++
returnData[returnPos] = new Object();
}
}
if (str == '!trap')
gotTrap = true;
if (str == '!fatal')
gotFatal = true;
if (str == '!done')
gotDone = true;
// Parse key-value pair
if (str.substr(0,1) == '=') {
var tmpPos:int = str.indexOf('=',1);
var tmpKey:String = str.substr(1,tmpPos-1);
var tmpVal:String = str.substr(tmpPos+1);
returnData[returnPos][tmpKey] = tmpVal;
}
// Reset tag
if (str.substr(0,1) == '!')
tag = "";
// Set tag
if (str.substr(0,5) == '.tag=')
tag = str.substr(5);
// Are there more packets available
if (bytesAvailable)
readResponse();
}
}
private function socketDataHandler(event:ProgressEvent):void {
readResponse();
}
}
}
// ApiEvent.as
//
// RouterOS API Event class
// Author: Håkon Nessjøen
// Date: 2. May 2009
//
package {
import flash.events.Event;
public class ApiEvent extends Event {
static public var RECEIVED:String = "received";
static public var LOGIN:String = "loggedin";
public var data:Array;
public var result:String;
public var tag:String;
public function ApiEvent(type:String, tg:String, dta:Array, res:String){
super(type);
data = dta;
result = res;
tag = tg;
}
}
}
And here’s an
Example
// Short example that outputs wireless registration-table every second
import ApiSocket;
import ApiEvent;
var sock:ApiSocket;
var myTimer:Timer = new Timer(1000);
myButton.addEventListener(MouseEvent.CLICK, testAPI);
myTimer.addEventListener(TimerEvent.TIMER, timedFunction);
function testAPI(evt:MouseEvent):void {
sock = new ApiSocket("172.17.1.1", 8728);
sock.addEventListener(ApiEvent.RECEIVED, receive);
sock.addEventListener(Event.CONNECT, connected);
sock.addEventListener(ApiEvent.LOGIN, loggedin);
}
function connected(evt:Event) {
trace("Connected. Logging in.");
sock.login("admin","password");
}
function loggedin(evt:ApiEvent) {
// result can be done, trap or fatal
if (evt.result == 'done') {
myTimer.start();
}
}
function timedFunction(e:TimerEvent) {
sock.sendRequest("/interface/wireless/registration-table/print", ".tag=mytag");
}
function receive(evt:ApiEvent) {
trace("Got Event with tag " + evt.tag + " result: " + evt.result);
if (evt.tag == 'mytag' && evt.result == 'done') {
trace("Got rows: " + evt.data.length);
for (var i:int = 0; i < evt.data.length; ++i) {
trace(evt.data[i]['mac-address'])
trace(" " + evt.data[i]['signal-strength'])
}
}
}
Anyways, the code is nice to use in Flash AIR applications, since Flash AIR doesn’t have any security limitations to connecting with sockets. But if you were to use this class in a SWF file, you would need to do the right measures to let Flash accept your “cross domain scripting”.