API ActionScript 3 class

From MikroTik Wiki
Jump to: navigation, search

These are ActionScript 3 classes for working with RouterOS v3 API. You can take it, edit it and use it as you need.

NOTE - The API implementation is not yet fully tested with large requests or replies. Please update this section if you have tested this. Also, this ActionScript probably works best in Flash AIR applications (opposed to swf flash files), since they have no security limitations on socket connections.

Class


// ApiSocket.as
//
// RouterOS API class
// Author: Håkon Nessjøen of Avelia AS
// 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 of Avelia AS
// 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;
		}
	}

}

Example 1


// 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'])
		}
	}
}

See also