Debian Codegraph @

src/mikrotik_plugin/routeros_api.php

raw
1 <?php
2 /*****************************
3 *
4 * * * Actualizado a la version 6.45.1
5 * * Nuevo api-ssl
6 *
7 * RouterOS PHP API class v1.6.1
8 * Author: Denis Basta
9 * Contributors:
10 * Maxi Dobladez <elmaxi[at]gmail[dot]com>
11 * Nick Barnes
12 * Ben Menking (ben [at] infotechsc [dot] com)
13 * Jeremy Jefferson (http://jeremyj.com)
14 * Cristian Deluxe (djcristiandeluxe [at] gmail [dot] com)
15 * Mikhail Moskalev (mmv.rus [at] gmail [dot] com)
16 *
17 * http://www.mikrotik.com
18 * http://wiki.mikrotik.com/wiki/API_PHP_class
19 *
20 ******************************/
21
22 class RouterosAPI
23 {
24 var $debug = false; // Show debug information
25 var $connected = false; // Connection state
26 var $port = 8728; // Port to connect to (default 8729 for ssl)
27 var $ssl = false; // Connect using SSL (must enable api-ssl in IP/Services)
28 var $timeout = 3; // Connection attempt timeout and data read timeout
29 var $attempts = 1; // Connection attempt count
30 var $delay = 2; // Delay between connection attempts in seconds
31
32 var $socket; // Variable for storing socket resource
33 var $error_no; // Variable for storing connection error number, if any
34 var $error_str; // Variable for storing connection error text, if any
35
36 /* Check, can be var used in foreach */
37 public function isIterable($var)
38 {
39 return $var !== null
40 && (is_array($var)
41 || $var instanceof Traversable
42 || $var instanceof Iterator
43 || $var instanceof IteratorAggregate
44 );
45 }
46
47 /**
48 * Print text for debug purposes
49 *
50 * @param string $text Text to print
51 *
52 * @return void
53 */
54 public function debug($text)
55 {
56 if ($this->debug) {
57 echo $text . "\n";
58 }
59 }
60
61
62 /**
63 *
64 *
65 * @param string $length
66 *
67 * @return void
68 */
69 public function encodeLength($length)
70 {
71 if ($length < 0x80) {
72 $length = chr($length);
73 } elseif ($length < 0x4000) {
74 $length |= 0x8000;
75 $length = chr(($length >> 8) & 0xFF) . chr($length & 0xFF);
76 } elseif ($length < 0x200000) {
77 $length |= 0xC00000;
78 $length = chr(($length >> 16) & 0xFF) . chr(($length >> 8) & 0xFF) . chr($length & 0xFF);
79 } elseif ($length < 0x10000000) {
80 $length |= 0xE0000000;
81 $length = chr(($length >> 24) & 0xFF) . chr(($length >> 16) & 0xFF) . chr(($length >> 8) & 0xFF) . chr($length & 0xFF);
82 } elseif ($length >= 0x10000000) {
83 $length = chr(0xF0) . chr(($length >> 24) & 0xFF) . chr(($length >> 16) & 0xFF) . chr(($length >> 8) & 0xFF) . chr($length & 0xFF);
84 }
85
86 return $length;
87 }
88
89
90 /**
91 * Login to RouterOS
92 *
93 * @param string $ip Hostname (IP or domain) of the RouterOS server
94 * @param string $login The RouterOS username
95 * @param string $password The RouterOS password
96 *
97 * @return boolean If we are connected or not
98 */
99 public function connect($ip, $login, $password,$port=8728)
100 {
101 for ($ATTEMPT = 1; $ATTEMPT <= $this->attempts; $ATTEMPT++) {
102 $this->connected = false;
103 $PROTOCOL = ($this->ssl ? 'ssl://' : '' );
104 $context = stream_context_create(array('ssl' => array('ciphers' => 'ADH:ALL', 'verify_peer' => false, 'verify_peer_name' => false)));
105 $this->debug('Connection attempt #' . $ATTEMPT . ' to ' . $PROTOCOL . $ip . ':' . $port . '...');
106 $this->socket = @stream_socket_client($PROTOCOL . $ip.':'. $port, $this->error_no, $this->error_str, $this->timeout, STREAM_CLIENT_CONNECT,$context);
107 if ($this->socket) {
108 socket_set_timeout($this->socket, $this->timeout);
109 $this->write('/login', false);
110 $this->write('=name=' . $login, false);
111 $this->write('=password=' . $password);
112 $RESPONSE = $this->read(false);
113 if (isset($RESPONSE[0])) {
114 if ($RESPONSE[0] == '!done') {
115 if (!isset($RESPONSE[1])) {
116 // Login method post-v6.43
117 $this->connected = true;
118 break;
119 } else {
120 // Login method pre-v6.43
121 $MATCHES = array();
122 if (preg_match_all('/[^=]+/i', $RESPONSE[1], $MATCHES)) {
123 if ($MATCHES[0][0] == 'ret' && strlen($MATCHES[0][1]) == 32) {
124 $this->write('/login', false);
125 $this->write('=name=' . $login, false);
126 $this->write('=response=00' . md5(chr(0) . $password . pack('H*', $MATCHES[0][1])));
127 $RESPONSE = $this->read(false);
128 if (isset($RESPONSE[0]) && $RESPONSE[0] == '!done') {
129 $this->connected = true;
130 break;
131 }
132 }
133 }
134 }
135 }
136 }
137 fclose($this->socket);
138 }
139 sleep($this->delay);
140 }
141
142 if ($this->connected) {
143 $this->debug('Connected...');
144 } else {
145 $this->debug('Error...');
146 }
147 return $this->connected;
148 }
149
150
151 /**
152 * Disconnect from RouterOS
153 *
154 * @return void
155 */
156 public function disconnect()
157 {
158 // let's make sure this socket is still valid. it may have been closed by something else
159 if( is_resource($this->socket) ) {
160 fclose($this->socket);
161 }
162 $this->connected = false;
163 $this->debug('Disconnected...');
164 }
165
166
167 /**
168 * Parse response from Router OS
169 *
170 * @param array $response Response data
171 *
172 * @return array Array with parsed data
173 */
174 public function parseResponse($response)
175 {
176 if (is_array($response)) {
177 $PARSED = array();
178 $CURRENT = null;
179 $singlevalue = null;
180 foreach ($response as $x) {
181 if (in_array($x, array('!fatal','!re','!trap'))) {
182 if ($x == '!re') {
183 $CURRENT =& $PARSED[];
184 } else {
185 $CURRENT =& $PARSED[$x][];
186 }
187 } elseif ($x != '!done') {
188 $MATCHES = array();
189 if (preg_match_all('/[^=]+/i', $x, $MATCHES)) {
190 if ($MATCHES[0][0] == 'ret') {
191 $singlevalue = $MATCHES[0][1];
192 }
193 $CURRENT[$MATCHES[0][0]] = (isset($MATCHES[0][1]) ? $MATCHES[0][1] : '');
194 }
195 }
196 }
197
198 if (empty($PARSED) && !is_null($singlevalue)) {
199 $PARSED = $singlevalue;
200 }
201
202 return $PARSED;
203 } else {
204 return array();
205 }
206 }
207
208
209 /**
210 * Parse response from Router OS
211 *
212 * @param array $response Response data
213 *
214 * @return array Array with parsed data
215 */
216 public function parseResponse4Smarty($response)
217 {
218 if (is_array($response)) {
219 $PARSED = array();
220 $CURRENT = null;
221 $singlevalue = null;
222 foreach ($response as $x) {
223 if (in_array($x, array('!fatal','!re','!trap'))) {
224 if ($x == '!re') {
225 $CURRENT =& $PARSED[];
226 } else {
227 $CURRENT =& $PARSED[$x][];
228 }
229 } elseif ($x != '!done') {
230 $MATCHES = array();
231 if (preg_match_all('/[^=]+/i', $x, $MATCHES)) {
232 if ($MATCHES[0][0] == 'ret') {
233 $singlevalue = $MATCHES[0][1];
234 }
235 $CURRENT[$MATCHES[0][0]] = (isset($MATCHES[0][1]) ? $MATCHES[0][1] : '');
236 }
237 }
238 }
239 foreach ($PARSED as $key => $value) {
240 $PARSED[$key] = $this->arrayChangeKeyName($value);
241 }
242 return $PARSED;
243 if (empty($PARSED) && !is_null($singlevalue)) {
244 $PARSED = $singlevalue;
245 }
246 } else {
247 return array();
248 }
249 }
250
251
252 /**
253 * Change "-" and "/" from array key to "_"
254 *
255 * @param array $array Input array
256 *
257 * @return array Array with changed key names
258 */
259 public function arrayChangeKeyName(&$array)
260 {
261 if (is_array($array)) {
262 foreach ($array as $k => $v) {
263 $tmp = str_replace("-", "_", $k);
264 $tmp = str_replace("/", "_", $tmp);
265 if ($tmp) {
266 $array_new[$tmp] = $v;
267 } else {
268 $array_new[$k] = $v;
269 }
270 }
271 return $array_new;
272 } else {
273 return $array;
274 }
275 }
276
277
278 /**
279 * Read data from Router OS
280 *
281 * @param boolean $parse Parse the data? default: true
282 *
283 * @return array Array with parsed or unparsed data
284 */
285 public function read($parse = true)
286 {
287 $RESPONSE = array();
288 $receiveddone = false;
289 while (true) {
290 // Read the first byte of input which gives us some or all of the length
291 // of the remaining reply.
292 $BYTE = ord(fread($this->socket, 1));
293 $LENGTH = 0;
294 // If the first bit is set then we need to remove the first four bits, shift left 8
295 // and then read another byte in.
296 // We repeat this for the second and third bits.
297 // If the fourth bit is set, we need to remove anything left in the first byte
298 // and then read in yet another byte.
299 if ($BYTE & 128) {
300 if (($BYTE & 192) == 128) {
301 $LENGTH = (($BYTE & 63) << 8) + ord(fread($this->socket, 1));
302 } else {
303 if (($BYTE & 224) == 192) {
304 $LENGTH = (($BYTE & 31) << 8) + ord(fread($this->socket, 1));
305 $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
306 } else {
307 if (($BYTE & 240) == 224) {
308 $LENGTH = (($BYTE & 15) << 8) + ord(fread($this->socket, 1));
309 $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
310 $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
311 } else {
312 $LENGTH = ord(fread($this->socket, 1));
313 $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
314 $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
315 $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
316 }
317 }
318 }
319 } else {
320 $LENGTH = $BYTE;
321 }
322
323 $_ = "";
324
325 // If we have got more characters to read, read them in.
326 if ($LENGTH > 0) {
327 $_ = "";
328 $retlen = 0;
329 while ($retlen < $LENGTH) {
330 $toread = $LENGTH - $retlen;
331 $_ .= fread($this->socket, $toread);
332 $retlen = strlen($_);
333 }
334 $RESPONSE[] = $_;
335 $this->debug('>>> [' . $retlen . '/' . $LENGTH . '] bytes read.');
336 }
337
338 // If we get a !done, make a note of it.
339 if ($_ == "!done") {
340 $receiveddone = true;
341 }
342
343 $STATUS = socket_get_status($this->socket);
344 if ($LENGTH > 0) {
345 $this->debug('>>> [' . $LENGTH . ', ' . $STATUS['unread_bytes'] . ']' . $_);
346 }
347
348 if ((!$this->connected && !$STATUS['unread_bytes']) || ($this->connected && !$STATUS['unread_bytes'] && $receiveddone)) {
349 break;
350 }
351 }
352
353 if ($parse) {
354 $RESPONSE = $this->parseResponse($RESPONSE);
355 }
356
357 return $RESPONSE;
358 }
359
360
361 /**
362 * Write (send) data to Router OS
363 *
364 * @param string $command A string with the command to send
365 * @param mixed $param2 If we set an integer, the command will send this data as a "tag"
366 * If we set it to boolean true, the funcion will send the comand and finish
367 * If we set it to boolean false, the funcion will send the comand and wait for next command
368 * Default: true
369 *
370 * @return boolean Return false if no command especified
371 */
372 public function write($command, $param2 = true)
373 {
374 if ($command) {
375 $data = explode("\n", $command);
376 foreach ($data as $com) {
377 $com = trim($com);
378 fwrite($this->socket, $this->encodeLength(strlen($com)) . $com);
379 $this->debug('<<< [' . strlen($com) . '] ' . $com);
380 }
381
382 if (gettype($param2) == 'integer') {
383 fwrite($this->socket, $this->encodeLength(strlen('.tag=' . $param2)) . '.tag=' . $param2 . chr(0));
384 $this->debug('<<< [' . strlen('.tag=' . $param2) . '] .tag=' . $param2);
385 } elseif (gettype($param2) == 'boolean') {
386 fwrite($this->socket, ($param2 ? chr(0) : ''));
387 }
388
389 return true;
390 } else {
391 return false;
392 }
393 }
394
395
396 /**
397 * Write (send) data to Router OS
398 *
399 * @param string $com A string with the command to send
400 * @param array $arr An array with arguments or queries
401 *
402 * @return array Array with parsed
403 */
404 public function comm($com, $arr = array())
405 {
406 $count = count($arr);
407 $this->write($com, !$arr);
408 $i = 0;
409 if ($this->isIterable($arr)) {
410 foreach ($arr as $k => $v) {
411 switch ($k[0]) {
412 case "?":
413 $el = "$k=$v";
414 break;
415 case "~":
416 $el = "$k~$v";
417 break;
418 default:
419 $el = "=$k=$v";
420 break;
421 }
422
423 $last = ($i++ == $count - 1);
424 $this->write($el, $last);
425 }
426 }
427
428 return $this->read();
429 }
430
431 /**
432 * Standard destructor
433 *
434 * @return void
435 */
436 public function __destruct()
437 {
438 $this->disconnect();
439 }
440 }