-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrouteros.class.php
793 lines (664 loc) · 20.2 KB
/
routeros.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
<?php
//! @class RouterOS
//! @brief Base class for handing RouterOS API interface. It implements methods of getting and setting values as well restarting router.
//! @author ayufan
//! @par Subversion:
//! https://svn.osk-net.pl/rosapi/trunk
//! @par License:
//! GPL: http://www.gnu.org/licenses/gpl.html
//! @remarks All commands accepts two forms of arguments. Either using string or using array. Prefered way is to use array.
class RouterOS
{
private $sock;
private $where;
private $tags = array();
private $tagIndex = 1;
private $dispatcher = array();
//! Read-only flag. If set to TRUE: RouterOS class will not change nor remove any item.
public $readOnly = FALSE;
function __destruct() {
@fclose($this->sock);
}
private function fread_secure($sock, $size) {
$data = '';
while(strlen($data) < $size) {
$rv = fread($sock, $size - strlen($data));
if($rv === false || $rv == '')
return false;
$data .= $rv;
}
return $data;
}
private function fwrite_secure($sock, $data) {
$bytes_to_write = strlen($data);
$bytes_written = 0;
while($bytes_written < $bytes_to_write) {
if($bytes_written == 0)
$rv = fwrite($sock, $data);
else
$rv = fwrite($sock, substr($data, $bytes_written));
if($rv === false || $rv == 0)
return $bytes_written == 0 ? false : $bytes_written;
$bytes_written += $rv;
}
return $bytes_written;
}
private function writeSock($cmd = '') {
//if(strlen($cmd) == 0)
// echo "<<< ---\n";
//else
// echo "<<< $cmd\n";
$l = strlen($cmd);
if($l < 0x80) {
$this->fwrite_secure($this->sock, chr($l));
}
else if($l < 0x4000) {
$l |= 0x8000;
$this->fwrite_secure($this->sock, chr(($l >> 8) & 0xFF) . chr($l & 0xFF));
}
else if($l < 0x200000) {
$l |= 0xC00000;
$this->fwrite_secure($this->sock, chr(($l >> 16) & 0xFF) . chr(($l >> 8) & 0xFF) . chr($l & 0xFF));
}
else if($l < 0x10000000) {
$l |= 0xE0000000;
$this->fwrite_secure($this->sock, chr(($l >> 24) & 0xFF) . chr(($l >> 16) & 0xFF) . chr(($l >> 8) & 0xFF) . chr($l & 0xFF));
}
else {
$this->fwrite_secure($this->sock, chr(0xF0) . chr(($l >> 24) & 0xFF) . chr(($l >> 16) & 0xFF) . chr(($l >> 8) & 0xFF) . chr($l & 0xFF));
}
$this->fwrite_secure($this->sock, $cmd);
}
private function readSock() {
$c = ord($this->fread_secure($this->sock, 1));
if(($c & 0x80) == 0x00) {
}
else if(($c & 0xC0) == 0x80) {
$c &= ~0xC0;
$c = ($c << 8) + ord($this->fread_secure($this->sock, 1));
}
else if(($c & 0xE0) == 0xC0) {
$c &= ~0xE0;
$c = ($c << 8) + ord($this->fread_secure($this->sock, 1));
$c = ($c << 8) + ord($this->fread_secure($this->sock, 1));
}
else if(($c & 0xF0) == 0xE0) {
$c &= ~0xF0;
$c = ($c << 8) + ord($this->fread_secure($this->sock, 1));
$c = ($c << 8) + ord($this->fread_secure($this->sock, 1));
$c = ($c << 8) + ord($this->fread_secure($this->sock, 1));
}
else {
$c = ord(fread($this->sock));
$c = ($c << 8) + ord($this->fread_secure($this->sock, 1));
$c = ($c << 8) + ord($this->fread_secure($this->sock, 1));
$c = ($c << 8) + ord($this->fread_secure($this->sock, 1));
}
if($c == 0) {
//echo ">>> ---\n";
return NULL;
}
$o = $this->fread_secure($this->sock, $c);
//echo ">>> $o\n";
return $o;
}
private function trap($args, $hide = FALSE) {
if($args['message'] && $args['message'] != 'interrupted')
echo "trap[".$this->where."]: ${args['message']}\n";
while($this->response() != '!done');
}
//! Connects to new MikroTik RouterOS
//! @param host ip address or dns name
//! @param login user login
//! @param password user password
//! @param port api service port
//! @return RouterOS class object
//! @par Usage
//! @code $conn = RouterOS::connect("192.168.10.11", "admin", "adminpassword"); @endcode
static function connect($host, $login, $password, $port = 8728, $timeout = 10) {
$self = new RouterOS();
// open socket
if(($self->sock = @fsockopen($host, 8728, $errno, $errstr, $timeout)) === FALSE)
return NULL;
stream_set_timeout($self->sock, $timeout);
// initiate login
$self->send('', 'login');
$type = $self->response($args);
if($type != '!done' || !isset($args['ret']))
return NULL;
// try to login
$self->send('', 'login', FALSE, array('name' => $login, 'response' => '00'.md5(chr(0).$password.pack('H*',$args['ret']))));
$type = $self->response($args);
if($type == '!done')
return $self;
else if($type == '!trap')
$self->trap($args);
unset($self);
return NULL;
}
//! Defines how long socket waits for data read/write.
//! @param timeout Set socket timeout in seconds.
public function setTimeout($timeout = 5) {
return stream_set_timeout($this->sock, $timeout);
}
private function send($cmd, $type, $proplist = FALSE, $args = FALSE, $tag = FALSE) {
$result = TRUE;
if(is_array($cmd))
$cmd = '/' . join('/', $cmd);
$cmd .= '/' . $type;
$this->where = $cmd;
// send command & args
$this->writeSock($cmd);
if($args) {
foreach($args as $key=>$value) {
if(is_int($key))
$this->writeSock("$value");
else
$this->writeSock("=$key=$value");
}
}
if($proplist)
$this->writeSock(".proplist=" . (is_array($proplist) ? join(',', $proplist) : $proplist));
if($tag) {
if(is_callable($tag)) {
$result = $this->tagIndex++;
$this->tags[$result] = $tag;
}
else {
$result = $tag;
}
$this->writeSock(".tag=$result");
}
$this->writeSock();
return $result;
}
private function response(&$args = FALSE, $dispatcher = FALSE) {
if($dispatcher && count($this->dispatcher)) {
$res = array_shift($this->dispatcher);
$args = $res["args"];
return $res["type"];
}
while(true) {
$args = array();
$type = FALSE;
// read response type
if($type = $this->readSock()) {
if($type[0] != '!') {
while($this->readSock());
return FALSE;
}
}
// read response parameters
while($line = $this->readSock()) {
if($line[0] == '=') {
$line = explode('=', $line, 3);
$args[$line[1]] = count($line) == 3 ? $line[2] : TRUE;
continue;
}
else {
$line = explode('=', $line, 2);
$args[$line[0]] = isset($line[1]) ? $line[1] : '';
}
}
unset($args['debug-info']);
if(isset($args[".tag"])) {
if($dispatcher)
return $type;
$this->dispatcher[] = array("tag" => $args[".tag"], "type" => $type, "args" => $args);
}
else {
return $type;
}
}
return FALSE;
}
//! Get all values for specified command
//! @param cmd @ref cmd
//! @param proplist list of values to get (string comma delimeted or array)
//! @param args @ref args
//! @param assoc name of associative key
//! @retval integer callback index
//! @retval array results
//! @par Usage
//! @code $conn->getall("/interface/wireless/registration-table"); @endcode
//! @code $conn->getall("/interface/wireless/registration-table", ".id,interface,mac-address", FALSE, "mac-address"); @endcode
//! @code $conn->getall(array("interface", "wireless", "registration-table"), array(".id", "interface", "mac-address"), FALSE, "mac-address"); @endcode
function getall($cmd, $proplist = FALSE, $args = array(), $assoc = FALSE, $callback = FALSE) {
$res = $this->send($cmd, 'getall', $proplist, $args, $callback);
if($proplist) {
if(!is_array($proplist))
$proplist = explode(',', $proplist);
$proplist = array_fill_keys($proplist, TRUE);
}
if($callback) {
return $res;
}
$ids = array();
// wait for response
while(true) {
$ret = array();
switch($type = $this->response($ret)) {
case '!re':
if($proplist)
$ret = array_intersect_key($ret, $proplist);
if(isset($ret['.id']))
if($assoc)
$ids[$ret[$assoc]] = $ret;
else
$ids[] = $ret;
else
foreach($ret as $key => $value)
$ids[$key] = $value;
break;
case '!trap':
$this->trap($ret);
return FALSE;
case '!done':
break 2;
default:
echo("getall: undefined type=$type\n");
return FALSE;
}
}
return $ids;
}
//! Set item or command value
//! @param cmd @ref cmd
//! @param args @ref args
//! @param callback @ref callback
//! @retval integer calback index
//! @retval boolean command execution status
//! @par Usage
//! @code $conn->set("/ip/firewall/filter", ".id=*10 chain=forward action=reject"); @endcode
function set($cmd, $args = array(), $callback = FALSE) {
if($this->readOnly)
return TRUE;
$res = $this->send($cmd, 'set', FALSE, $args, $callback);
if($callback) {
return $res;
}
switch($type = $this->response($ret)) {
case '!done':
return TRUE;
case '!trap':
$this->trap($ret);
return FALSE;
default:
echo("set: undefined type\n");
return FALSE;
}
}
//! Reboots RouterOS
//! @retval boolean
function reboot() {
$this->send('/system', 'reboot', FALSE, FALSE);
echo "!! rebooting...\n";
sleep(5);
switch($type = $this->response($ret)) {
case '!done':
return TRUE;
case '!trap':
$this->trap($ret);
return FALSE;
default:
return TRUE;
}
}
//! Cancel last or tagged command
//! @param callback @ref callback
//! @param tag callback index for cancel
//! @retval integer callback index
//! @retval boolean cancel status
function cancel($tag = FALSE, $callback = FALSE) {
if(is_callable($tag)) {
$tag = array_search($tag, $this->tags);
if($tag === FALSE) {
echo "cancel: undefined tag\n";
return FALSE;
}
}
$res = $this->send('', 'cancel', FALSE, array(".tag" => $tag), FALSE, $callback);
if($callback) {
return $res;
}
switch($type = $this->response($ret)) {
case '!done':
return TRUE;
case '!trap':
$this->trap($ret);
return FALSE;
default:
echo("set: undefined type\n");
return FALSE;
}
}
//! Uses /tool/fetch to download file from remote server. It can be used for example to fetch latest RouterOS releases.
//! @param url e.g. http://66.228.113.58/routeros-mipsbe-4.3.npk
//! @param callback @ref callback
//! @retval integer callback index
//! @retval boolean fetch status
//! @par Usage
//! @code $conn->fetchurl("http://66.228.113.58/routeros-mipsbe-4.3.npk"); @endcode
function fetchurl($url, $callback = FALSE) {
$finished = FALSE;
echo ".. downloading $url\n";
$res = $this->send('/tool', 'fetch', FALSE, array('url' => $url), $callback);
if($callback) {
return $res;
}
while(true) {
switch($type = $this->response($ret)) {
case '!done':
return TRUE;
case '!trap':
$this->trap($ret);
return FALSE;
case '!re':
switch($ret['status']) {
case 'connecting':
case 'requesting':
break;
case 'downloading':
if(!$ret['total'])
break;
$progress = round(intval($ret['downloaded'])*100 / intval($ret['total']), 1);
echo ".. ${ret['downloaded']} of ${ret['total']} ($progress%) within ${ret['duration']}\n";
break;
case 'finished':
echo ".. downloaded!\n";
$this->cancel();
$finished = TRUE;
break;
case 'failed':
echo "!! failed!\n";
$this->cancel();
break;
default:
echo("fetch: undefined response (${ret['status']})\n");
return FALSE;
}
break;
default:
echo("fetch: undefined type\n");
return FALSE;
}
flush();
}
return $finished;
}
//! Move specified item before another item.
//! @param id item index to move
//! @param callback @ref callback
//! @retval integer callback index
//! @retval boolean move status
//! @par Usage
//! @code $conn->move("/ip/firewall/filter", "*5", "*10"); @endcode
function move($cmd, $id, $before, $callback = FALSE) {
if($this->readOnly)
return TRUE;
$res = $this->send($cmd, 'move', FALSE, array('numbers' => $id, 'destination' => $before), $callback);
if($callback) {
return $res;
}
switch($type = $this->response($ret)) {
case '!done':
return TRUE;
case '!trap':
$this->trap($ret);
return FALSE;
default:
echo("set: undefined type\n");
return FALSE;
}
}
//! Add an new item for command.
//! @param cmd @ref cmd
//! @param args @ref args
//! @param callback @ref callback
//! @retval integer callback index
//! @retval string new item index
//! @retval boolean add status
//! @par Usage
//! @code $conn->add("/ip/firewall/filter", "chain=forward action=drop"); @endcode
function add($cmd, $args = array(), $callback = FALSE) {
if($this->readOnly)
return TRUE;
$res = $this->send($cmd, 'add', FALSE, $args, $callback);
if($callback) {
return $res;
}
switch($type = $this->response($ret)) {
case '!done':
if(isset($ret['ret']))
return $ret['ret'];
return TRUE;
case '!trap':
$this->trap($ret);
return FALSE;
default:
echo("set: undefined type\n");
return FALSE;
}
}
//! Remove specified item or array of items for command
//! @see getall
//! @param id item or array of items to remove
//! @param callback @ref callback
//! @retval integer callback index
//! @retval boolean remove status
//! @par Usage
//! @code $conn->remove("/ip/firewall/filter", "*10"); @endcode
//! @code $conn->remove("/ip/firewall/filter", array("*10", "*20")); @endcode
function remove($cmd, $id, $callback = FALSE) {
if($this->readOnly)
return TRUE;
$res = $this->send($cmd, 'remove', FALSE, array('.id' => is_array($id) ? join(',', $id) : $id), $callback);
if($callback) {
return $res;
}
switch($type = $this->response($ret)) {
case '!done':
return TRUE;
case '!trap':
$this->trap($ret);
return FALSE;
default:
echo("remove: undefined type\n");
return FALSE;
}
}
//! Unset value for specified item
//! @param cmd @ref cmd
//! @param callback @ref callback
//! @param id item index
//! @param value what to unset
//! @retval integer callback index
//! @retval boolean remove status
//! @par Usage
//! @code $conn->unsett("/queue/simple", "*10", "time"); @endcode
function unsett($cmd, $id, $value, $callback = FALSE) {
if($this->readOnly)
return TRUE;
$res = $this->send($cmd, 'unset', FALSE, array('numbers' => $id, 'value-name' => $value), $callback);
if($callback) {
return $res;
}
switch($type = $this->response($ret)) {
case '!done':
return TRUE;
case '!trap':
$this->trap($ret);
return FALSE;
default:
echo("unset: undefined type\n");
return FALSE;
}
}
//! Perform a remote wireless scan. Before scanning set stream interval to larger value than duration.
//! @param id index of wireless interface
//! @param duration how long to scan
//! @param callback @ref callback
//! @retval integer callback index
//! @retval array results where key is bssid
//! @retval boolean FALSE on error
//! @par Usage
//! @code $interfaces = $conn->getall("/interface/wireless", ".id,name", FALSE, "name");
//! $results = $conn->scan($interfaces["backbone"][".id"]); @endcode
function scan($id, $duration="00:10:00", $callback = FALSE) {
$res = $this->send('/interface/wireless', 'scan', FALSE, array('.id' => $id, 'duration' => $duration), $callback);
if($callback) {
return $res;
}
$results = array();
while(true) {
$ret = array();
switch($type = $this->response($ret)) {
case '!done':
return $results;
case '!re':
$results[$ret['address']] = $ret;
break;
case '!trap':
$this->trap($ret);
return FALSE;
default:
echo("scan: undefined type: $type\n");
return FALSE;
}
}
}
//! Perform a wireless frequency scanner. Before scanning set stream interval to larger value than duration.
//! @see scan
//! @param id index of wireless interface
//! @param callback @ref callback
//! @retval integer callback index
//! @retval array results where key is frequency
//! @retval boolean FALSE on error
function freqmon($id, $duration="00:02:00", $callback = FALSE) {
$res = $this->send('/interface/wireless', 'frequency-monitor', FALSE, array('.id' => $id, 'duration' => $duration), $callback);
if($callback) {
return $res;
}
$results = array();
while(true) {
$ret = array();
switch($type = $this->response($ret)) {
case '!done':
return $results;
case '!re':
$results[$ret['freq']][] = $ret;
break;
case '!trap':
$this->trap($ret);
return FALSE;
default:
echo("scan: undefined type: $type\n");
return FALSE;
}
}
}
function listen($cmd, $args = FALSE, $callback) {
return $this->send($cmd, 'listen', FALSE, $args, $callback);
}
//! Perform a bandwidth-test. Supports only transmit and it should be used as asynchronous command, ie. callback.
//! @param address ip address or dns name
//! @param protocol udp[:packet_size] or tcp
//! @param callback @ref callback
//! @retval integer callback index
//! @retval boolean test result
function btest($address, $speed = "1M", $protocol = "tcp", $callback = FALSE) {
list($proto, $count) = explode(":", $protocol, 2);
$args = array(
"address" => $address,
"direction" => "transmit",
"local-tx-speed" => $speed);
if($proto == "tcp") {
$count = min(max(intval($count), 1), 20);
$args["protocol"] = "tcp";
$args["tcp-connection-count"] = $count;
}
else if($proto == "udp") {
$count = min(max(intval($count), 30), 1500);
$args["protocol"] = "udp";
$args["local-udp-tx-size"] = $count;
}
else {
echo("invalid protocol: $proto\n");
return FALSE;
}
$res = $this->send('/tool', 'bandwidth-test', FALSE, $args, $callback);
//echo ".. running btest[$res] to $address ($speed/$protocol)...\n";
if($callback) {
return $res;
}
while(true) {
$ret = array();
switch($type = $this->response($ret)) {
case '!done':
return TRUE;
case '!re':
print_r($ret);
break;
case '!trap':
$this->trap($ret);
return FALSE;
default:
echo("btest: undefined type: $type\n");
return FALSE;
}
}
}
//! Dispatches comming messages from server to functions executed as callbacks.
//! @param continue flag to manually break listener loop (it can be done from callback). Initial value should be set to TRUE.
//! @retval boolean TRUE if there is one or more pending functions
//! @par Usage
//! @code $continue = TRUE; $conn->dispatch($continue); @endcode
function dispatch(&$continue) {
while($continue || count($this->tags)) {
switch($type = $this->response($ret, TRUE)) {
case '!re':
if(isset($ret['.tag'])) {
$callback = $this->tags[$ret['.tag']];
if(is_callable($callback))
$callback($this, TRUE, $ret);
}
break;
case '!done':
if(isset($ret['.tag'])) {
$callback = $this->tags[$ret['.tag']];
if(is_callable($callback))
call_user_func($callback, $this, TRUE, NULL);
unset($this->tags[$ret['.tag']]);
}
break;
case '!trap':
if(isset($ret['.tag'])) {
$callback = $this->tags[$ret['.tag']];
if(is_callable($callback))
call_user_func($callback, $this, FALSE, $ret);
unset($this->tags[$ret['.tag']]);
}
break;
default:
echo("dispatch: undefined type : $type\n");
return FALSE;
}
}
return count($this->tags) != 0;
}
};
//! @defgroup test Test section
//! @{
//! @anchor cmd @par Commands:
//! @code /ip/firewall/filter @endcode
//! @code array("ip", "firewall", "filter") @endcode
//! @anchor args @par Arguments:
//! @code chain=forward action=drop in-interface=ether1 @endcode
//! @code array("chain"=>"forward", "action"=>"drop", "in-interface"=>"ether1") @endcode
//! @anchor callback @par Callbacks:
//! @code function myCallbackFunction($conn, $state, $results); @endcode
//! @param conn RouterOS object
//! @param state indicate callback boolean state. TRUE the response is either "!done" or "!re". FALSE the response is "!trap"
//! @param results contains additional arguments for response. If NULL callback got "!done" status otherwise contains associative array of results from API server.
//! @}
?>